0

I'm trying to query an elastic search cluster. The index name is titles and _type is title. When I put the type in the request URL, the filtering works as expected:

POST http://esendpoint.com/titles/title/_search?

The body:

"query": {
    "filtered": {
      "query": {

        "bool": {
          "should": [
            {  "term" : {"_docTitleIds" : "65d-7ab2-41d4-a928-300accfc8ab7"}}
          ]
        }
      }

    }
  }

However if I add the _type title in the query body, and not in the URL I get all results under the index titles. But when used in the URL, I get results only from the type title

POST http://esendpoint.com/titles/_search

The body:

"query": {
        "filtered": {
          "query": {

            "bool": {
              "should": [
                {  "term" : {"_type" : "title"}},
                {  "term" : {"_docTitleIds" : "65d-7ab2-41d4-a928-300accfc8ab7"}}
              ]
            }
          }

        }
      }

I'm not able to follow why this is happening.

user1692342
  • 5,007
  • 11
  • 69
  • 128
  • You should tell what error you're getting. Note that you're missing a comma after the `_type` constraint. – Val Sep 25 '19 at 05:09
  • @Val Sorry, I missed out the comma. I updated the question. I don't get an exception, but I get results from the entire index rather the specific type like how it is when passed via the URL. – user1692342 Sep 25 '19 at 05:16

1 Answers1

0

You need to use filter (AND) instead of should (OR):

{
  "query": {
    "filtered": {
      "filter": {
        "bool": {
          "must": [
            {
              "term": {
                "_type": "title"
              }
            },
            {
              "term": {
                "_docTitleIds": "65d-7ab2-41d4-a928-300accfc8ab7"
              }
            }
          ]
        }
      }
    }
  }
}

The query below is for ES 2 and later:

{
  "query": {
    "bool": {
      "filter": [
        {
          "term": {
            "_type": "title"
          }
        },
        {
          "term": {
            "_docTitleIds": "65d-7ab2-41d4-a928-300accfc8ab7"
          }
        }
      ]
    }
  }
}
Val
  • 207,596
  • 13
  • 358
  • 360
  • I get the exception: `SearchPhaseExecutionException[Failed to execute phase [query], all shards failed; shardFailures` – user1692342 Sep 25 '19 at 05:28
  • Also in my example I use filtered instead of filter and have query inside filtered. Maybe that is an issue? – user1692342 Sep 25 '19 at 05:29
  • I've elastic search 1.7.1 if it matters. The error cause is `bool query does not support [filter]` – user1692342 Sep 25 '19 at 05:32
  • I've updated my answer to match 1.7.1 but be aware [of this](https://stackoverflow.com/questions/40519806/no-query-registered-for-filtered/40521602#40521602) when you migrate to a more recent version. – Val Sep 25 '19 at 06:14