Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

elasticsearch query nested array of objects

Hi I am trying to get a query to filter based on values in an array of objects, the structure is like this

{
  "_index": "test",
  "_type": "home",
  "_id": "1247816",
  "_score": 1,
  "_source": {
    "TranCust": {
      "CustId": 1247816,
      "sourceNodeName": "SRC"
    },
    "TranList": [
      {
        "TranId": 2431015,
        "batchNr": "211"
      },
      {
        "TranId": 2431016,
        "batchNr": "213"
      }
    ]
  }
}

as an example, i would like to find all documents with a TranId of 2431015, my query looks like this

{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "TranList",
            "query": {
              "bool": {
                "must": [
                  {
                    "match": {
                      "TranId": "2431015"
                    }
                  }
                ]
              }
            }
          }
        }
      ]
    }
  }
}

it seems to return no results, is there a better way to try and write this query ?

EDIT, here are the mappings put in

{
 "mappings": {
    "home": {
        "properties": {
            "TranCust": {
                "type": "object"
                }
            },
            "TranList": {
                "type": "nested"
            }
        }
    }
 }
}
like image 757
user2168435 Avatar asked Nov 09 '15 09:11

user2168435


2 Answers

Not sure what was your ES version, but the following should ideally work for ES 6.x+ versions. You don't actually need to wrap your nested query with bool:must

{
    "query": {
        "nested" : {
            "path" : "TranList",
            "query" : {
                "bool" : {
                    "must" : [
                        { "match" : {"TranList.TranId" : "2431015"} }
                    ]    
                }
            }
        }
    }
}

like image 186
tugcem Avatar answered Oct 07 '22 01:10

tugcem


ok so after lots of attempts this is how i got it to work

{"query": {
"bool": {
  "must": [
    {
      "nested": {
        "path": "TranList", 
        "query": {
          "bool": {
            "must": [ 
              { "match": { "TranList.TranId ": "2431015" }}
            ]
    }}}}
  ]
}}
}
like image 45
user2168435 Avatar answered Oct 06 '22 23:10

user2168435