Filter ids across multiple indexes


(Cameron Craig) #1

I'm querying all searchable fields across all indexes and need to filter certain ids of documents returned from different indexes, how would I be able to filter/query for these kinds of results?


(David Pilato) #2

This? https://www.elastic.co/guide/en/elasticsearch/reference/6.2/query-dsl-ids-query.html


(Cameron Craig) #3

Yes, I need to make the ID's query work, but across multiple indexes. I.e. specify an array of ID's and the index that the different arrays of ID's need to be filtered on


(David Pilato) #4
DELETE test1,test2 
PUT test1/doc/1
{
  "foo": "bar"
}
PUT test1/doc/2
{
  "foo": "bar"
}
PUT test2/doc/1
{
  "foo": "bar"
}
PUT test2/doc/2
{
  "foo": "bar"
}
GET _search
{
  "query": {
    "bool": {
      "should": [
        {
          "bool": {
            "must": [
              {
                "term": {
                  "_index": {
                    "value": "test2"
                  }
                }
              },
              {
                "ids": {
                  "values": [
                    "1"
                  ]
                }
              }
            ]
          }
        },        {
          "bool": {
            "must": [
              {
                "term": {
                  "_index": {
                    "value": "test1"
                  }
                }
              },
              {
                "ids": {
                  "values": [
                    "2"
                  ]
                }
              }
            ]
          }
        }

      ]
    }
  }
}

Gives:

{
  "took": 20,
  "timed_out": false,
  "_shards": {
    "total": 17,
    "successful": 17,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 2,
    "hits": [
      {
        "_index": "test1",
        "_type": "doc",
        "_id": "2",
        "_score": 2,
        "_source": {
          "foo": "bar"
        }
      },
      {
        "_index": "test2",
        "_type": "doc",
        "_id": "1",
        "_score": 2,
        "_source": {
          "foo": "bar"
        }
      }
    ]
  }
}

(Cameron Craig) #5

Would this support multiple search terms? I'll still need the ability to search for documents on specific properties along with limiting the ids that get returned


(David Pilato) #6

You can add whatever clause wherever you want in the bool tree.


(Cameron Craig) #7

It looks like this is going to do what I need, thank you so much for the help dadoonet!


(Cameron Craig) #8

I'm actually running into a slight hiccup. By specifying additional "must" fields in the query with the "ids" param I am getting unwanted results. I am thinking I need to move the "ids" part of the query into a "filter" so that this doesn't happen?