对数组索引的 Elasticsearch 查询

Tha*_*igs 5 elasticsearch

如何在 elasticsearch 中按数组的索引查询/过滤?

我有一个这样的文件:-

PUT /edi832/record/1
{
    "LIN": [ "UP", "123456789" ]
}
Run Code Online (Sandbox Code Playgroud)

我想搜索LIN[0]是否为“UP”并且LIN[1] 是否存在。

谢谢。

Vin*_*han 3

这可能看起来像黑客,但它肯定会起作用。首先,我们应用令牌计数类型和多字段来捕获令牌数量作为字段。所以映射看起来像这样 -

{
    "record" : {
        "properties" : {
            "LIN" : {
                "type" : "string",
                "fields" : {
                    "word_count": {
                        "type" : "token_count",
                        "store" : "yes",
                        "analyzer" : "standard"
                    }
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

链接 - http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/mapping-core-types.html#token_count

因此,要检查第二个字段是否存在,就像检查该字段值是否大于或等于 2 一样简单。接下来我们可以使用令牌过滤器来检查位置 0 是否存在令牌“up”。我们可以使用脚本过滤器来检查这一点。因此,像下面这样的查询应该有效 -

{
  "query": {
    "filtered": {
      "query": {
        "range": {
          "LIN.word_count": {
            "gte": 2
          }
        }
      },
      "filter": {
        "script": {
          "script": "for(pos : _index['LIN'].get('up',_POSITIONS)){ if(pos.position == 0) { return true}};return false;"
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

高级脚本 - http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/modules-advanced-scripting.html

脚本过滤器 - http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-script-filter.html