[英]In Elasticsearch, how do I search string on multiple fields from multi-level nested objects
In Elasticsearch 6, I have data with nested objects like this:在 Elasticsearch 6 中,我有这样的嵌套对象的数据:
{
"brands" :
[
{
"brand_name" : "xyz",
"products" :
[
{
"title" : "test",
"mrp" : 100,
"sp" : 90,
"status" : 1
},
{
"title" : "test1",
"mrp" : 50,
"sp" : 45,
"status" : 1
}
]
},
{
"brand_name" : "aaa",
"products" :
[
{
"title" : "xyz",
"mrp" : 100,
"sp" : 90,
"status" : 1
},
{
"title" : "abc",
"mrp" : 50,
"sp" : 45,
"status" : 1
}
]
}
]
}
I want to search from either from the field brand_name or from the field title.我想从字段brand_name 或字段标题中进行搜索。 And I want return all results in same inner_hits.我想以相同的inner_hits返回所有结果。
For example : If I input the search string as "xyz" it should return both brands object with correspondent product object.例如:如果我将搜索字符串输入为“xyz”,它应该返回两个品牌对象和相应的产品对象。 If I input the search string as "test" it should return only first brand array with only first product object.如果我将搜索字符串输入为“test”,它应该只返回第一个品牌数组和第一个产品对象。
How can I achieve this.我怎样才能做到这一点。 Any ideas?有任何想法吗?
I have tried with the nested path query like this:我试过这样的嵌套路径查询:
{
"query": {
"bool": {
"must": [
{
"nested": {
"path": "brands",
"query": {
"bool": {
"should": [
{
"term": {
"brands.brand_name": "xyz"
}
},
{
"term": {
"brands.brand_name.keyword": "aaa"
}
},
{
"nested": {
"path": "brands.products",
"query": {
"bool": {
"should": [
{
"match": {
"brands.products.title": "xyz"
}
}
]
}
},
"inner_hits": {}
}
}
]
}
},
"inner_hits": {}
}
}
]
}
}
}
But this query returning with multiple inner_hits response with multiple array objects for each brands and for each products.但是这个查询返回多个 inner_hits 响应,每个品牌和每个产品都有多个数组对象。
I want the response like all brand names which is matching with the string should list under one array and all the products should list under another array under same inner_hits.我希望与字符串匹配的所有品牌名称等响应应列在一个数组下,所有产品应列在同一inner_hits下的另一个数组下。
Since you want the inner hits to be different based on where the match has happened ie brands.brand_name
or brands.products.title
, you can have two queries one for brand name and other for product title as independent nested queries.由于您希望内部命中根据匹配发生的位置而不同,即brands.brand_name
或brands.products.title
,您可以有两个查询,一个是品牌名称,另一个是产品标题,作为独立的嵌套查询。 These queries then should be inside should
clause of a bool
query.这些查询应该在bool
查询的should
子句中。 Each of the nested query should have its own inner_hits
as below:每个嵌套查询都应该有自己的inner_hits
,如下所示:
{
"query": {
"bool": {
"should": [
{
"nested": {
"path": "brands",
"inner_hits": {},
"query": {
"term": {
"brands.brand_name.keyword": "test"
}
}
}
},
{
"nested": {
"path": "brands.products",
"inner_hits": {},
"query": {
"term": {
"brands.products.title": "test"
}
}
}
}
]
}
},
"_source": false
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.