ElasticSearch脚本:检查数组是否包含一个值 [英] ElasticSearch Scripting: check if array contains a value
问题描述
假设我已经创建了一个这样的文件:
Let's say I have created a document like this:
PUT idx/type/1
{
"the_field": [1,2,3]
}
我可以检索我的文档使用GET / idx / type / 1:
I can retrieve my document using GET /idx/type/1:
{
"_index": "idx",
"_type": "type",
"_id": "1",
"_version": 1,
"found": true,
"_source": {
"the_field": [
1,
2,
3
]
}
}
现在,我想检查字段the_field是否包含值2.
我知道我可以使用一个术语子句,但是我需要使用过滤器脚本来检查它,所以我试过:
Now, I want to check if the field "the_field" contains the value 2. I know I can use a term clause, but I need to check this using a filter script, so I tried:
POST /idx/typ/_search
{
"query": {
"match_all": {}
},
"filter": {
"script": {
"script": "doc['the_field'].values.contains(2)"
}
}
}
并得到n o结果:
{
"took": 6,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 0,
"max_score": null,
"hits": []
}
}
要测试我的mevl脚本语法是否正确,我尝试这样做:
To test if my mevl script syntax is right, I tried doing this:
POST /idx/type/_search
{
"query": {
"match_all": {}
},
"filter": {
"script": {
"script": "[1,2,3].contains(3)"
}
}
}
并获得正确的结果:
{
"took": 1,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"failed": 0
},
"hits": {
"total": 1,
"max_score": 1,
"hits": [
{
"_index": "idx",
"_type": "type",
"_id": "1",
"_score": 1,
"_source": {
"the_field": [
1,
2,
3
]
}
}
]
}
}
我做错了什么?
我认为doc ['the_field']。值应该返回[1,2,3],不是吗?如果是这样,我的代码应该可以工作。
I think doc['the_field'].values should return [1,2,3], is not it? If so, my code should work.
有人可以帮助我吗?
谢谢!
Does anybody can help me? Thank you!
更新
当我更换所有[1,2,3]在我的代码中有[a,b,c],它的作品。任何想法?
When I replace all the [1, 2, 3] in my code with ["a"," b", "c"], it works. Any idea?
推荐答案
正在使用a,b,c,因为 the_field
默认存储在Elasticsearch中作为字符串而不是整数。您可以通过以下方式检查映射来验证:
It is working with "a", "b", "c" because the_field
is being stored in Elasticsearch by default as a string and not an integer. You can validate by checking the mapping with:
$ curl -XGET 'http://localhost:9200/idx/type/_mapping'
以下内容应设置适当的字段类型:
The following should set the appropriate field type:
$ curl -XPUT 'http://localhost:9200/idx/type/_mapping' -d '
{
"type" : {
"properties" : {
"the_field" : {"type" : "integer" }
}
}
}
更新映射,重新索引数据,看看是否有效。请参阅 PUT Mapping API 需要时提供额外的指导。
Update the mapping, re-index your data and see if that works. Please see the PUT Mapping API for additional guidance if needed.
这篇关于ElasticSearch脚本:检查数组是否包含一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!