简体   繁体   中英

Query ElasticSearch by array filter length

I have a prop containing an array of integers:

_source: {
  counts: [
    11,
    7,
    18,
    3,
    22
  ]
}

From another post I know that I can filter by a range using:

{
  "query": {
    "bool": {
      "must": {
        "match_all": {}   
      },  
      "filter": {
        "range": {
          "counts": {
            "gte": 10,
            "lte": 20
          }
        }
      }
    }
  }
}

However, I need to additionally know if the range match count is greater than a certain number. For instance, I only want records back which have less than 3 counts matching between 10 and 20.

Mapping used:

{
  "properties" : {
    "counts" : {
      "type" :    "integer"
    }
  }
}

These are the docs I indexed:

{
  "took": 4,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 3,
    "max_score": 1,
    "hits": [
      {
        "_index": "test_index",
        "_type": "test",
        "_id": "2",
        "_score": 1,
        "_source": {
          "counts": [
            13,
            17
          ]
        }
      },
      {
        "_index": "test_index",
        "_type": "test",
        "_id": "1",
        "_score": 1,
        "_source": {
          "counts": [
            11,
            7,
            18,
            3,
            22
          ]
        }
      },
      {
        "_index": "test_index",
        "_type": "test",
        "_id": "3",
        "_score": 1,
        "_source": {
          "counts": [
            11,
            19
          ]
        }
      }
    ]
  }
}

Now try this query:

    {
          "query": {
            "bool": {
              "must": {
                "match_all": {}   
              },  
              "filter": [
                        {"script" : { "script" : "doc['counts'].values.size() < 4" }},
                         {"range": { "counts": { "gte": 10, "lte": 20 } }}
                        ]
                }
          }
 }

Results: Only doc id 2 and 3 are returned. Doc 1 is not returned.

{
  "took": 29,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 1,
    "hits": [
      {
        "_index": "test_index",
        "_type": "test",
        "_id": "2",
        "_score": 1,
        "_source": {
          "counts": [
            13,
            17
          ]
        }
      },
      {
        "_index": "test_index",
        "_type": "test",
        "_id": "3",
        "_score": 1,
        "_source": {
          "counts": [
            11,
            19
          ]
        }
      }
    ]
  }
}

Is this what you are trying to do?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM