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 楼答案
设置文本索引
首先,需要在要执行文本查询的字段上设置文本索引
如果使用Spring data mongo在数据库中插入文档,可以使用
@TextIndexed
注释,插入文档时将生成索引如果文档已插入数据库,则需要手动构建文本索引
在the build and config of your mongoTemplate之后,您可以传递文本索引/
构建文本查询