Dinesh Kumar P
Dinesh Kumar P

Reputation: 1178

Elastic Search NEST - How to have multiple levels of filters in search

I would like to have multiple levels of filters to derive a result set using NEST API in Elastic Search. Is it possible to query the results of another filter...? If yes can I do that in multiple levels?

My requirement is like a User is allowed to select / unselect options of various fields.

Example: There are totally 1000 documents in my index 'people'. There may be 3 ListBoxs, 1) City 2) Favourite Food 3) Favourite Colour. If user selects a city it filters out 600 documents. Out of those 600 documents I would like to filter Favourite food, which may result with some 300 documents. Now further I would like to filter with resp. to favourite movie to retrieve 50 documents out of previously derived 300 documents.

Upvotes: 0

Views: 713

Answers (1)

Garry Welding
Garry Welding

Reputation: 3609

You don't need to query within filters to achieve what you want. Just use filtered queries, http://www.elasticsearch.org/guide/en/elasticsearch/reference/current/query-dsl-filtered-query.html, and provide several filters. In your instance I would assume you would do something like this for your first query:

{
    "filtered" : {
        "query" : {
            "match_all" : { }
        },
        "filter" : {
            "and" : [
                {
                    "term" : {
                        "city" : "some city"
                    }
                }
            ]
        }
    }
}

You would then return the results from that and display them. You'd then let them select the next filter and do the following:

{
    "filtered" : {
        "query" : {
            "match_all" : { }
        },
        "filter" : {
            "and" : [
                {
                    "term" : {
                        "city" : "some city"
                    }
                },
                {
                    "term" : {
                        "food" : "some food"
                    }
                }
            ]
        }
    }
}

You'd then rinse and repeat for the 3 filter param:

{
    "filtered" : {
        "query" : {
            "match_all" : { }
        },
        "filter" : {
            "and" : [
                {
                    "term" : {
                        "city" : "some city"
                    }
                },
                {
                    "term" : {
                        "food" : "some food"
                    }
                },
                {
                    "term" : {
                        "colour" : "some colour"
                    }
                }
            ]
        }
    }
}

I haven't tested this, but the principle is sound and will work.

Upvotes: 3

Related Questions