How to create full text search query in mongodb with spring-data?

前端 未结 1 950
暖寄归人
暖寄归人 2021-01-14 18:53

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

In mongo shell it look like that:

<
相关标签:
1条回答
  • 2021-01-14 19:40

    Setup Text indexes

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

    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();
    

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

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

    Building your text query

    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
    }
    
    0 讨论(0)
提交回复
热议问题