spring数据mongodb支持Atlas搜索吗?需要一个例子



我正试图从java应用程序中找到如何使用mongo Atlas搜索索引,该应用程序使用spring数据mongodb来查询数据,任何人都可以共享一个例子吗?

我发现的代码如下,但这是用于MongoDB文本搜索的,尽管它正在工作,但不确定它是否使用Atlas搜索定义的索引。

TextQuery textQuery = TextQuery.queryText(new TextCriteria().matchingAny(text)).sortByScore();
textQuery.fields().include("cast").include("title").include("id");
List<Movies> movies = mongoOperations
.find(textQuery, Movies.class);

我想要一些使用spring数据mongodb的java代码来进行以下查询:

[
{
$search: {
index: 'cast-fullplot',
text: {
query: 'sandeep',
path: {
'wildcard': '*'
}
}
}
}
]

如果有人能解释MongoDB Text Search与Mongo Atlas Search的不同之处,以及借助java spring data MongoDB使用Atalas Search的正确方法,那将非常有帮助。

如何使用spring数据mongodb编写以下代码:

Arrays.asList(new Document("$search", 
new Document("index", "cast-fullplot")
.append("text", 
new Document("query", "sandeep")
.append("path", 
new Document("wildcard", "*")))), 
new Document())

是的,spring-data-mongo支持聚合管道,您将使用它来执行查询。

您需要定义一个文档列表,并按照查询中定义的步骤以正确的顺序。Atlas Search必须是目前的第一步。您可以使用Mongo-Atlas接口将查询转换为聚合管道,他们可以选择以您选择的语言导出管道数组。然后,您只需要执行查询并将响应列表映射到实体类。

你可以看到下面的例子:

public class SearchRepositoryImpl implements SearchRepositoryCustom {
private final MongoClient mongoClient;
public SearchRepositoryImpl(MongoClient mongoClient) {
this.mongoClient = mongoClient;
}
@Override
public List<SearchEntity> searchByFilter(String text) {
// You can add codec configuration in your database object. This might be needed to map
// your object to the mongodb data
MongoDatabase database = mongoClient.getDatabase("aggregation");
MongoCollection<Document> collection = database.getCollection("restaurants");
List<Document> pipeline = List.of(new Document("$search", new Document("index", "default2")
.append("text", new Document("query", "Many people").append("path", new Document("wildcard", "*")))));
List<SearchEntity> searchEntityList = new ArrayList<>();
collection.aggregate(pipeline, SearchEntity.class).forEach(searchEntityList::add);
return searchEntityList;
}

}

最新更新