Lior Kupers
Lior Kupers

Reputation: 847

Using query_string search with post_filter

I'm trying to search for a city using query_string and asterix (query: `${city}*`) while also filtering the results by countryId. The query works well without filtering for countryId, but when adding the filter it finds nothing. Boty city and countryId were mapped as text.

Code:

const elasticsearch = require('elasticsearch');

...

this.client = new elasticsearch.Client({
            hosts: [this._serviceUri]
        });

...

// The interesting part:
const results = await this.client.search({
            index: 'cities',
            body: {
                query: {
                    query_string: {
                        query: `${city}*`,
                        fields: ['city', 'countryId'],
                        // type: 'best_fields'
                    }
                },
                post_filter: { term: { countryId } }
            }
        });

How can I filter the results with post_filter or something alike correctly?

UPDATE: Here is how the mapping looks like:

mappings: {
        _doc: {
            properties: {
                "city": {type: 'text'},
                "countryId": {type: 'text'}
            }
        }
    }

Upvotes: 1

Views: 175

Answers (1)

Val
Val

Reputation: 217474

I would do it this way, without resorting to post_filter:

// The interesting part:
const results = await this.client.search({
        index: 'cities',
        body: {
            query: {
                bool: {
                    must: {
                        query_string: {
                            query: `${city}*`,
                            fields: ['city', 'countryId'],
                            // type: 'best_fields'
                        }
                    },
                    filter: {
                        term: { 
                            countryId: `${countryId}`,
                        }
                    }
                }
            }
        }
    });

Upvotes: 1

Related Questions