Использование запроса query_string с post_filter - PullRequest
1 голос
/ 25 марта 2019

Я пытаюсь найти город, используя query_string и звездочку (query: `${city}*`), а также фильтрую результаты по countryId. Запрос работает хорошо без фильтрации для countryId, но при добавлении фильтра он ничего не находит. Boty city и countryId были отображены как text.

Код:

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 } }
            }
        });

Как правильно отфильтровать результаты с помощью post_filter или чего-то подобного?

UPDATE: Вот как выглядит отображение:

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

1 Ответ

1 голос
/ 26 марта 2019

Я бы сделал это так, не прибегая к 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}`,
                        }
                    }
                }
            }
        }
    });
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...