如何使用elasticsearch搜索多个字段?

How to search through multiple fields with elasticsearch?

elasticsearch如何实现多字段搜索?我尝试了很多查询,但 none 的问题得到了解决。我希望搜索不区分大小写,并且一个字段比另一个字段更重要。我的查询如下所示:

const eQuery = {
    query: {
        query_string: {
            query: `*SOME_CONTENT_HERE*`,
            fields: ['title^3', 'description'],
            default_operator: 'OR',
        },
    },
}
esClient.search(
    {
        index: 'movies',
        body: eQuery,
    },
    function(error, response) {
    },
)

映射如下所示:

{
    mappings: {
        my_index_type: {
            dynamic_templates: [{ string: { mapping: { type: 'keyword' }, match_mapping_type: 'string' } }],
            properties: {
                created_at: { type: 'long' },
                description: { type: 'keyword' },
                title: { type: 'keyword' },
                url: { type: 'keyword' },
            },
        },
        _default_: {
            dynamic_templates: [{ string: { mapping: { type: 'keyword' }, match_mapping_type: 'string' } }],
        },
    },
}

问题出在您的字段描述和标题映射中 type: keyword。不分析关键字类型字段,即它们存储索引数据,就像它被发送到 elastic 一样。当您想要匹配唯一 ID 等内容时,它就会派上用场。阅读:https://www.elastic.co/guide/en/elasticsearch/reference/current/keyword.html

您应该阅读 elasticsearch 的分析器。您可以非常轻松地创建您的自定义分析器,它可以以不同的方式更改您发送给它们的数据,例如在索引或搜索之前将所有内容小写。 幸运的是,有 pre-configured 个用于基本操作(例如小写)的分析器。如果您将描述和标题字段的类型更改为 type: text,您的查询将有效。 阅读:https://www.elastic.co/guide/en/elasticsearch/reference/current/text.html

此外,我看到您为索引配置了动态模板。因此,如果您没有明确指定索引的映射,则所有字符串字段(如描述和标题)都将被视为类型:关键字。 如果您像这样建立索引:

PUT index_name
{
  "mappings": {
    index_type: {
      "properties": {
        "description": {"type": "text"},
        "title": {"type": "text"}, ...
      }
    }
  }
}

你的问题应该已经解决了。这是因为 type: text 字段默认由标准分析器分析,它将输入小写,等等。阅读:https://www.elastic.co/guide/en/elasticsearch/reference/current/analysis-standard-analyzer.html