在ES中有一个对象数组
我想只匹配一个对象(在数组内)中的两个字段匹配的文档。
我的问题是这样的。假设我有3个文档(外部文档被删除),其中我有一个对象数组,例如// Doc 1
"questionAnswers": [
{
"question": "First yes no question",
"answer": "Yes"
},
{
"question": "Second yes no question",
"answer": "No"
}
]
// Doc 2
"questionAnswers": [
{
"question": "First yes no question",
"answer": "No"
},
{
"question": "Second yes no question",
"answer": "No"
}
]
// Doc 3
"questionAnswers": [
{
"question": "First yes no question",
"answer": "No"
},
{
"question": "Second yes no question",
"answer": "Yes"
}
]
我的查询是
{
"from": 0,
"size": 25,
"query": {
"bool": {
"filter": [
{
"match": {
"questionAnswers.question.keyword": "First yes no question"
}
},
{
"match": {
"questionAnswers.answer": "Yes"
}
}
]
}
}
}
我目前得到匹配的文档1和3。而我只希望第一个文档匹配其中question = first yes no question and answer = yes
如何做到这一点?
您需要将questionAnswers
字段定义为嵌套类型,以便可以单独查询其中的每个数组对象,并且可以使用inner_hits
在结果中只获得匹配的文档。
添加一个带有索引映射、搜索查询和搜索结果的工作示例
指数映射:
{
"mappings": {
"properties": {
"questionAnswers": {
"type": "nested"
}
}
}
}
搜索查询:
{
"query": {
"nested": {
"path": "questionAnswers",
"query": {
"bool": {
"filter": [
{
"match": {
"questionAnswers.question.keyword": "First yes no question"
}
},
{
"match": {
"questionAnswers.answer": "Yes"
}
}
]
}
},
"score_mode": "avg",
"inner_hits": {}
}
}
}
搜索结果:
"hits": [
{
"_index": "68760699",
"_type": "_doc",
"_id": "1",
"_score": 0.0,
"_source": {
"questionAnswers": [
{
"question": "First yes no question",
"answer": "Yes"
},
{
"question": "Second yes no question",
"answer": "No"
}
]
},
"inner_hits": {
"questionAnswers": {
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 0.0,
"hits": [
{
"_index": "68760699",
"_type": "_doc",
"_id": "1",
"_nested": {
"field": "questionAnswers",
"offset": 0
},
"_score": 0.0,
"_source": {
"question": "First yes no question", //note this
"answer": "Yes"
}
}
]
}
}
}
}
]