我正在尝试创建一个 Elasticsearch 查询来匹配数组内对象内的多个字段。
例如,我要查询的 Elastic Search 结构类似于以下内容:
"hits": [
{
"_index": "titles",
"_type": "title",
...
"_source": {
...
"genres": [
{
"code": "adventure",
"priority": 1
},
{
"code": "action",
"priority": 2
},
{
"code": "horror",
"priority": 3
}
],
...
},
...
]
我想要做的是匹配具有特定流派/优先级配对的标题。例如,我尝试将所有标题与 code=action
和 priority=1
匹配,但我的查询返回的结果太多。上面的标题在这个例子中被命中,因为流派列表包含一个流派与 code=action
和另一个匹配 priority=1
的流派。我的查询类似于以下内容:
"query": {
"bool": {
"filter": [
{
"bool": {
"must":[
{"term": {
"genres.code": {
"value": "action",
"boost": 1.0
}
}},
{"term": {
"genres.priority": {
"value": 1,
"boost": 1.0
}
}}
]
}
},
...
}
是否有任何方法可以形成查询,以便将标题与包含 priority=1
和 code=action
的单一流派相匹配?
最佳答案
我已经重现了你的问题。我添加了以下映射
PUT titles
{
"mappings": {
"title": {
"properties": {
"author": {
"type": "text"
},
"genres": {
"type": "nested"
}
}
}
}
}
然后我将值添加到索引中。这是插入的内容
"hits": {
"total": 3,
"max_score": 1,
"hits": [
{
"_index": "titles",
"_type": "title",
"_id": "2",
"_score": 1,
"_source": {
"author": "Author 1",
"genres": [
{
"code": "adventure",
"priority": 2
},
{
"code": "action",
"priority": 3
},
{
"code": "horror",
"priority": 1
}
]
}
},
{
"_index": "titles",
"_type": "title",
"_id": "1",
"_score": 1,
"_source": {
"author": "Author 2",
"genres": [
{
"code": "adventure",
"priority": 3
},
{
"code": "action",
"priority": 1
},
{
"code": "horror",
"priority": 2
}
]
}
},
{
"_index": "titles",
"_type": "title",
"_id": "3",
"_score": 1,
"_source": {
"author": "Author 3",
"genres": [
{
"code": "adventure",
"priority": 3
},
{
"code": "action",
"priority": 1
},
{
"code": "horror",
"priority": 2
}
]
}
}
]
}
我的查询是:
GET titles/title/_search
{
"query": {
"nested": {
"path": "genres",
"query": {
"bool": {
"must": [
{
"term": {
"genres.code": {
"value": "horror"
}
}
},
{
"term": {
"genres.priority": {
"value": 1
}
}
}
]
}
}
}
}
}
查询返回
"_source": {
"author": "Author 1",
"genres": [
{
"code": "adventure",
"priority": 2
},
{
"code": "action",
"priority": 3
},
{
"code": "horror",
"priority": 1
}
]
}
此标题是唯一具有代码 = '恐怖' 和优先级 = 1 的标题。
关于json - 如何在 Elasticsearch 中匹配每个数组项的多个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56245615/