有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用springdata在mongodb中创建全文搜索查询?

我有java或kotlin上的spring数据mogodb应用程序,需要通过spring模板向mongodb创建文本搜索请求

在mongo shell中,它看起来是这样的:

  db.stores.find(
   { $text: { $search: "java coffee shop" } },
   { score: { $meta: "textScore" } }
  ).sort( { score: { $meta: "textScore" } } )

我已经尝试过做一些事情,但这并不完全是我所需要的:

@override fun getSearchedFiles(searchQuery: String, pageNumber: Long, pageSize: Long, direction: Sort.Direction, sortColumn: String): MutableList<SystemFile> {

    val matching = TextCriteria.forDefaultLanguage().matching(searchQuery)


    val match = MatchOperation(matching)
    val sort = SortOperation(Sort(direction, sortColumn))
    val skip = SkipOperation((pageNumber * pageSize))
    val limit = LimitOperation(pageSize)

    val aggregation = Aggregation
            .newAggregation(match, skip, limit)
            .withOptions(Aggregation.newAggregationOptions().allowDiskUse(true).build())

    val mappedResults = template.aggregate(aggregation, "files", SystemFile::class.java).mappedResults


    return mappedResults
} 

可能有人已经在使用java在mongodb上进行文本搜索,请与我们分享您的知识)


共 (1) 个答案

  1. # 1 楼答案

    设置文本索引

    首先,需要在要执行文本查询的字段上设置文本索引

    如果使用Spring data mongo在数据库中插入文档,可以使用@TextIndexed注释,插入文档时将生成索引

    @Document
    class MyObject{
      @TextIndexed(weight=3) String title;
      @TextIndexed String description;
    }
    

    如果文档已插入数据库,则需要手动构建文本索引

    TextIndexDefinition textIndex = new TextIndexDefinitionBuilder()
      .onField("title", 3)
      .onField("description")
      .build();
    

    the build and config of your mongoTemplate之后,您可以传递文本索引/

    template.indexOps(MyObject.class).ensureIndex(textIndex);
    

    构建文本查询

    List<MyObject> getSearchedFiles(String textQuery){
      TextQuery textQuery = TextQuery.queryText(new TextCriteria().matchingAny(textQuery)).sortByScore();
      List<MyObject> result = mongoTemplate.find(textQuery, MyObject.class, "myCollection");
      return result
    }