如何在 Elasticsearch 的列表中获取足够的数据
How do I get just enough data in a list in Elasticsearch
假设我在 Elasticsearch 索引中有一个文档,如下所示
{
"data": [
{
"color": "RED",
"qty": 3
},
{
"color": "BLACK",
"qty": 1
}, {
"color": "BLUE",
"qty": 0
}
]
}
我只需要黑色。
有什么方法可以像下面这样获取足够的数据。
{
"data": [
{
"color": "BLACK",
"qty": 1
}
]
}
Elasticsearch returns 整个文档,如果有任何字段匹配。如果要查找匹配的嵌套文档,可以创建 data
数组 nested in your index mapping, write a nested query that filters data.color
by its value, which is BLACK in your case and use inner_hits 来查找匹配的嵌套文档。
您可以使用 source filtering 来只检索您想要的字段,但它只会按字段过滤,而不是按字段值过滤。
您可以使用 script field 生成仅具有数组中特定值的新字段。以下是示例查询:
{
"_source": {
"excludes": "data"
},
"query": {
"match_all": {}
},
"script_fields": {
"address": {
"script": {
"lang": "painless",
"source": """
List li = new ArrayList();
if(params['_source']['data'] != null)
{
for(p in params['_source']['data'])
{
if( p.color == 'BLACK')
li.add(p);
}
}
return li;
"""
}
}
}
}
响应:
"hits" : [
{
"_index" : "sample1",
"_type" : "_doc",
"_id" : "tUc6338BMCbs63yKTqj_",
"_score" : 1.0,
"_source" : { },
"fields" : {
"address" : [
{
"color" : "BLACK",
"qty" : 1
}
]
}
}
]
假设我在 Elasticsearch 索引中有一个文档,如下所示
{
"data": [
{
"color": "RED",
"qty": 3
},
{
"color": "BLACK",
"qty": 1
}, {
"color": "BLUE",
"qty": 0
}
]
}
我只需要黑色。 有什么方法可以像下面这样获取足够的数据。
{
"data": [
{
"color": "BLACK",
"qty": 1
}
]
}
Elasticsearch returns 整个文档,如果有任何字段匹配。如果要查找匹配的嵌套文档,可以创建 data
数组 nested in your index mapping, write a nested query that filters data.color
by its value, which is BLACK in your case and use inner_hits 来查找匹配的嵌套文档。
您可以使用 source filtering 来只检索您想要的字段,但它只会按字段过滤,而不是按字段值过滤。
您可以使用 script field 生成仅具有数组中特定值的新字段。以下是示例查询:
{
"_source": {
"excludes": "data"
},
"query": {
"match_all": {}
},
"script_fields": {
"address": {
"script": {
"lang": "painless",
"source": """
List li = new ArrayList();
if(params['_source']['data'] != null)
{
for(p in params['_source']['data'])
{
if( p.color == 'BLACK')
li.add(p);
}
}
return li;
"""
}
}
}
}
响应:
"hits" : [
{
"_index" : "sample1",
"_type" : "_doc",
"_id" : "tUc6338BMCbs63yKTqj_",
"_score" : 1.0,
"_source" : { },
"fields" : {
"address" : [
{
"color" : "BLACK",
"qty" : 1
}
]
}
}
]