First filter then run nested query

I have document with mapping:

{
    "properties": {
        "title": {"type": "text"},
        "added": {"type": "date"},
        "pdf_url": {"type": "text"},
        "blocks": {"type": "nested"}
    }
}

I plan to have a lot of documents. So I want to firstly filter documents for example with "added" field and then run query on my "nested" field.

This is my attempt to do it:

"query": {
    "filter": {
        "range": {
            "added": {"gte": "2015-01-01"}
        }
    },
    "nested": {
        "path": "blocks",
        "query": {
            "match": {
                "blocks.block_text": {
                    "query": "my query",
                    "fuzziness": "auto"
                },
            }
        },
        "inner_hits": {
            "highlight": {
                "fields": {
                    "blocks.block_text": {}
                }
            }
        }
    }
}

And I get elasticsearch.BadRequestError: BadRequestError(400, 'parsing_exception', 'unknown query [filter]')

I tried also wrap everything into "bool" but then I get similar error with "nested".

I kinda can achieve my result with this query. But firstly I am afraid that with large dataset it won't be efficient. Secondly I don't want filtered value having impact on score

"query": {
    "bool": {
        "must": [
            {
                "match": {
                    "title": {
                        "query": "title"
                    }
                }
            },
            {
                "nested": {
                    "path": "blocks",
                    "query": {
                        "match": {
                            "blocks.block_text": {
                                "query": "my qury",
                                "fuzziness": "auto"
                            },
                        }
                    },
                    "inner_hits": {
                        "highlight": {
                            "fields": {
                                "blocks.block_text": {}
                            }
                        }
                    }
                }
            }
        ]
    }
}

Hi @Michal_Bogusz

Add in your bool query the filter query.

 "bool": {
      "filter": [
        {
          "range": {
            "added": {
              "gte": "2015-01-01"
            }
          }
        }
      ],
     "must": [
        ....
      ]
1 Like

Works like charm, thank you

1 Like

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.