thirty
thirty

Reputation: 11

Elasticsearch 5.2 nested query for multi terms

nested document look like this

{
    "userid": "123",
    "usertag": [
        {
            "tag": "A",
            "logcreatetime": "2017-01-14"
        },
        {
            "tag": "C",
            "logcreatetime": "2017-01-17"
        }
    ]
},
{
    "userid": "456",
    "usertag": [
        {
            "tag": "A",
            "logcreatetime": "2017-01-12"
        },
        {
            "tag": "B",
            "logcreatetime": "2017-01-19"
        }
    ]
},
..... 

usertag object is nested mapping, how to get user id by 2017-01-12 to 2017-01-19 , has tag A and B? thanks sorry for my english.

Upvotes: 1

Views: 365

Answers (1)

Pavel Vasilev
Pavel Vasilev

Reputation: 1042

I'm assuming you've indexed your logcreatetime as Date field, so you can use the following query:

curl -XGET http://localhost:9200/my_users/_search -d '
{
  "query": {
    "bool": {
      "must": [ {
        "nested": {
          "path": "usertag",
          "query": {
            "bool": {
              "must": [
                { "match": { "usertag.tag": "A" }},
                { "range" : {
                    "usertag.logcreatetime" : {
                      "gte": "2017-01-12",
                      "lte": "2017-01-19"
                    }
                }}
              ]
            }
          }
        }
      }, {
        "nested": {
          "path": "usertag",
          "query": {
            "bool": {
              "must": [
                { "match": { "usertag.tag": "B" }},
                { "range" : {
                    "usertag.logcreatetime" : {
                      "gte": "2017-01-12",
                      "lte": "2017-01-19"
                    }
                }}
              ]
            }
          }
        }
      }]
    }
  }
}'

The limitation of syntax is that you can look for particular child which both has particular tag AND its logcreatetime lies within given range. But in order to ensure you'll have two children you should combine two nested queries into 2 must clauses of top-level bool.

Upvotes: 1

Related Questions