我正在使用带弹簧数据弹性的elasticsearch。并尝试使用多搜索。问题是搜索wprking与类字段,它不使用嵌套字段。我的映射如下所示
{
"archieve": {
"mappings": {
"author": {
"properties": {
"books": {
"type": "nested",
"properties": {
"id": {
"type": "long"
},
"name": {
"type": "string",
"analyzer": "standard"
}
}
},
"id": {
"type": "long"
},
"firstName": {
"type": "string",
"analyzer": "standard"
},
"lastName": {
"type": "string",
"analyzer": "standard"
}
}
}
}
}
}
我有一个使用searchQuery的端点,如:
@GetMapping(value = "/es/archieve/multi/{keyword}")
public Page<Author> getBrandMulti(@PathVariable String keyword, Pageable pageable) {
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(QueryBuilders.multiMatchQuery(keyword)
.field("firstName", 1.2f)
.field("books.name", 1.1f)
.type(MultiMatchQueryBuilder.Type.CROSS_FIELDS)
.fuzziness(Fuzziness.TWO)
)
.withIndices("archieve")
.withTypes("author")
.withPageable(pageable)
.build();
return elasticsearchTemplate.queryForPage(searchQuery, Author.class);
}
问题是查询不适用于 嵌套字段 。是否有任何建议,问候?
更新
实际上,可以将嵌套对象查询为
NativeSearchQueryBuilder()
.withQuery(QueryBuilders.nestedQuery("books",
QueryBuilders.termQuery("books.name", searchKey)))
无论如何要连接两个查询,比如
NativeSearchQueryBuilder()
.withQuery(Query1)
.withQuery(Query1)
.build();
答案 0 :(得分:1)
正如the document所说,当您查询嵌套字段时,您必须使用嵌套查询:
由于嵌套对象被索引为单独的隐藏文档,因此我们无法直接查询它们。相反,我们必须使用嵌套查询来访问它们:
回到spring数据,我更喜欢使用Query
的方式,IMO更具可读性:
@Query(" {" +
" \"bool\": {\n" +
" \"should\": [\n" +
" {\n" +
" \"multi_match\": {\n" +
" \"query\": \"?0\",\n" +
" \"fields\": [\"firstName\"]\n" +
" }\n" +
" },\n" +
" {\n" +
" \"nested\": {\n" +
" \"path\": \"books\",\n" +
" \"query\": {\n" +
" \"match\": {\n" +
" \"books.name\": \"?0\"\n" +
" }}\n" +
" }\n" +
" } ]\n" +
" }" +
"}")
Page<EsBrand> findByNameOrBooks(String info, Pageable pageable);
您可以将此签名放在您的repo界面中,该弹簧将实现代理以执行其他工作。