Sammaye
Sammaye

Reputation: 43884

How are filters applied in Elastic Search?

In ES are filters applied before the query?

Say, for example, I am doing a really slow fuzzy search but I am only doing it on a small date range. For an example you can look below (PHP):

$res=$client->search(array('index' => 'main', 'body' => array(
    'query' => array(
    'bool' => array(
        'should' => array(
            array('wildcard' => array('title' => '*123*')),
        )
    )
    ),
    'filter' => array(
        'and' => array(
            array('range' => array('created' => array('gte' => date('c',time()-3600), 'lte' => date('c',time()+3600))))
        )
    ),
    'sort' => array()
)));

Will the filter be applied before trying that slower search?

Logic would dictate that filters are run and then the query but I would like to be sure.

Upvotes: 2

Views: 1589

Answers (1)

Alex Brasetvik
Alex Brasetvik

Reputation: 11744

If you use the filtered-query, then filters will be applied before documents are scored.

This will generally speed things up quite a lot. However, the fuzzy query will still be using the input to build a larger query regardless of the filters.

When you use filter right on the search object, then the query will first run without respecting the filter, then documents will be filtered out of the hits - whereas facets will remain unfiltered.

Therefore, you should almost always use the filtered-query, at least when you are not using facets.

Upvotes: 2

Related Questions