如何在 mongo-spring 聚合中使用文本搜索



如何将一个简单的 mongo shell $match短语翻译成等价的在爪哇的 mongo-spring 中 - 使用聚合?

$match: { $text: { $search: "read" } } 

Spring-data 内置了对文本搜索的支持。

我使用了以下依赖项:

<dependency>
    <groupId>org.springframework.data</groupId>
    <artifactId>spring-data-mongodb</artifactId>
    <version>1.8.2.RELEASE</version>
</dependency>

请尝试以下语法:

TextCriteria criteria = TextCriteria.forDefaultLanguage().matchingAny("read");
Query query = TextQuery.queryText(criteria);    
List<klass> list = mongoTemplate.find(query, klass, "collection_name");

有关更多详细信息,请参阅此处。

要在聚合中执行相同的操作,请使用以下语法:

BasicDBObject match = new BasicDBObject("$match", 
                new BasicDBObject("$text", new BasicDBObject("$search", "COST")));
List<DBObject> aggregationList = new ArrayList<DBObject>();
aggregationList.add(match);
AggregationOutput aggregationOutput = mongoTemplate.getCollection("categoryMaster")
        .aggregate(aggregationList);
List<DBObject> dbObjects = (List<DBObject>) aggregationOutput.results();

在您的klass中转换此dbobjects,如下所示:

for(DBObject dbObject : dbObjects) {
    mongoTemplate.getConverter().read(klass, dbObject);
}

最新更新