luzny
luzny

Reputation: 2400

Filter by id in array and return only item with id, Elasticsearch 1.7

How to filter offers array by id field and return in results object with searched id?

Current search correctly find data by id in offers array but it also returns all objects it:

GET activities/activity/_search
{
   "query": {
      "filtered": {
         "filter": {
            "bool": {
               "must": [
                  {
                    "term": {
                      "offers.id": "12"
                    }
                  }
               ]
            }
         }
      }
   }
}

Current results, I would like to filter offers and get only that with "id": 12:

"hits": [
   {
      "_index": "activities",
      "_type": "activity",
      "_id": "AVtr4-UV81wMr8KFD246",
      "_score": null,
      "_source": {
         "offers": [
            {
               "title": "merge",
               "id": 11
            },
            {
               "title": "order test",
               "id": 12
            }
         ],
         "event": "candidate_remove",
         "created_at": "2017-04-14T09:55:49.115174Z"
      }
   }
]

mapping for offers in activity type:

"offers": {
   "type": "nested",
   "include_in_parent": true,
   "properties": {
      "id": {
         "type": "long"
      },
      "title": {
         "type": "string",
         "index": "not_analyzed"
      }
   }
},

Upvotes: 0

Views: 1543

Answers (1)

Andrei Stefan
Andrei Stefan

Reputation: 52368

You need inner_hits functionality and a nested query:

{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must": [
            {
              "nested": {
                "path": "offers",
                "query": {
                  "term": {
                    "offers.id": "12"
                  }
                },
                "inner_hits":{}
              }
            }
          ]
        }
      }
    }
  }
}

this will add another section in the response called inner_hits where it's showing the matching nested documents.

If you don't need the original offers value, you could add something like this to the original query:

{
  "_source": {"exclude": "offers"}, 
  "query": {
    "filtered": {

Upvotes: 1

Related Questions