假设我创建了一个这样的文档:
PUT idx/type/1 { "the_field": [1,2,3] }
我可以使用GET/idx/type/1检索我的文档:
{ "_index": "idx", "_type": "type", "_id": "1", "_version": 1, "found": true, "_source": { "the_field": [ 1, 2, 3 ] } }
现在,我想检查字段"the_field"是否包含值2.我知道我可以使用term子句,但我需要使用过滤器脚本来检查这个,所以我试过:
POST /idx/typ/_search { "query": { "match_all": {} }, "filter": { "script": { "script": "doc['the_field'].values.contains(2)" } } }
并没有得到任何结果:
{ "took": 6, "timed_out": false, "_shards": { "total": 5, "successful": 5, "failed": 0 }, "hits": { "total": 0, "max_score": null, "hits": [] } }
要测试我的mevl脚本语法是否正确,我尝试这样做:
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],不是吗?如果是这样,我的代码应该工作.
有人可以帮帮我吗?谢谢!
UPDATE
当我用["a","b","c"]替换我的代码中的所有[1,2,3]时,它可以工作.任何的想法?
它使用"a","b","c",因为the_field
默认情况下存储在Elasticsearch中作为字符串而不是整数.您可以通过检查映射来验证:
$ curl -XGET 'http://localhost:9200/idx/type/_mapping'
以下应设置适当的字段类型:
$ curl -XPUT 'http://localhost:9200/idx/type/_mapping' -d ' { "type" : { "properties" : { "the_field" : {"type" : "integer" } } } }
更新映射,重新索引数据并查看是否有效.如果需要,请参阅PUT Mapping API以获取其他指导.