本文介绍了如何在spring数据的mongodb中创建全文搜索查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java或Kotlin上都有spring-data-mogodb应用程序,并且需要通过spring模板向mongodb创建文本搜索请求.

I have spring-data-mogodb application on java or kotlin, and need create text search request to mongodb by spring template.

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

In mongo shell it look like that:

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

我已经尝试做某事,但这并不是我真正需要的:

I already tried to do something but it is not exactly what i need:

@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上进行文本搜索的人,请与我们分享您的知识)

May be someone already working with text searching on mongodb with java, please share your knowledge with us )

推荐答案

设置文本索引

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

Setup Text indexes

First you need to set up text indexes on the fields on which you want to perform your text query.

如果您正在使用Spring data mongo将文档插入数据库中,则可以使用@TextIndexed批注,并且在插入文档时将建立索引.

If you are using Spring data mongo to insert your documents in your database, you can use @TextIndexed annotation and indexes will be built while inserting your document.

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

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

If your document are already inserted in your database, you need to build your text indexes manually

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

的构建和配置之后您的mongoTemplate ,您可以传递文本索引/

After the build and config of your mongoTemplate you can pass your text indexes/

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
}

这篇关于如何在spring数据的mongodb中创建全文搜索查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-26 08:57