弹性搜索-条件投影



我知道我们可以在Elastic Search中使用投影来影响文档的哪些字段被返回或不被返回——类似于其他区域中的投影。然而,我也可以这样做投影吗?如果字段不满足特定条件,那么字段(或者更重要的是数组元素(就会被过滤掉?

假设ES中索引的文档如下所示:

{
"identificationString": "XYZ-123",
"localElements": [{
"name": "table",
"languageCode": "en"
}, {
"name": "mesa",
"languageCode": "es"
}],
"author": "Jon Snow",
"department": "Wood Work"
}

为了创建这个索引,我使用了例如:

curl -X PUT "localhost:9200/my-index?pretty" -H 'Content-Type: application/json' -d'
{
"mappings": {
"properties": {
"identificationString": {
"type": "text"
},
"localElements": {
"type": "nested",
"properties": {
"name": { "type": "text"  },  
"languageCode": { "type": "text"  }  
}
},
"author": {
"type": "text"
},
"department": {
"type": "text"
},
}
}
}
'

为了索引上述文件,我使用了:

curl -X POST "localhost:9200/my-index/_doc/?pretty" -H 'Content-Type: application/json' -d'
{
"identificationString": "XYZ-123",
"localElements": [{
"name": "table",
"languageCode": "en"
}, {
"name": "mesa",
"languageCode": "es"
}],
"author": "Jon Snow",
"department": "Wood Work"
}
'

如果我只想返回例如identificationStringlocalElements,我可以这样做:

curl -X GET "localhost:9200/my-index/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"match_all": {}
}, 
"fields": ["identificationString", "localElements.*"], 
"_source": false
}
'
'

或者类似的:

curl -X GET "localhost:9200/my-index/_search?pretty" -H 'Content-Type: application/json' -d'
{
"query": {
"match_all": {}
},
"_source": ["identificationString", "localElements.*"]
}
'

然而,是否也有一种方法可以只返回那些满足特定条件的localElement?例如,只有那些具有特定languageCode?我想过滤掉那些不符合特定条件的元素——我不想在回应中看到它们。当然,我可以在我的应用程序中实现这个逻辑,但我想知道Elastic Search是否也能做到这一点?

您可以将inner_hits与嵌套查询一起使用

{
"query": {
"nested": {
"path": "localElements",
"query": {
"bool": {
"must": {
"match": {
"localElements.languageCode": "es"
}
}
}
},
"inner_hits": {}
}
}
}

搜索结果将是

"hits": [
{
"_index": "67805874",
"_type": "_doc",
"_id": "1",
"_score": 0.6931471,
"_source": {
"identificationString": "XYZ-123",
"localElements": [
{
"name": "table",
"languageCode": "en"
},
{
"name": "mesa",
"languageCode": "es"
}
],
"author": "Jon Snow",
"department": "Wood Work"
},
"inner_hits": {
"localElements": {
"hits": {
"total": {
"value": 1,
"relation": "eq"
},
"max_score": 0.6931471,
"hits": [
{
"_index": "67805874",
"_type": "_doc",
"_id": "1",
"_nested": {
"field": "localElements",
"offset": 1
},
"_score": 0.6931471,
"_source": {
"name": "mesa",
"languageCode": "es"         // note this
}
}
]
}
}
}
}
]

最新更新