如何使用Elasticsearch在查询时指定不同的分析器?

Luc*_*ano 5 elasticsearch

我想在查询时使用不同的分析器来编写我的查询.

我从" 控制分析 " 文档中读到了这一点:

[...]搜索时的完整序列:

  • 分析器在查询本身中定义,否则
  • search_analyzer在字段映射中定义,否则
  • 分析器在字段映射中定义,否则
  • 分析器在索引设置中命名为default_search,默认为
  • 分析器在索引设置中命名为default,默认为
  • 标准分析仪

但我不知道如何编写查询以便为不同的子句指定不同的分析器:

"query"  => [
    "bool" => [
        "must"   => [
            {
                "match": ["my_field": "My query"]
                "<ANALYZER>": <ANALYZER_1>
            }
        ],
        "should" => [
            {
                "match": ["my_field": "My query"]
                "<ANALYZER>": <ANALYZER_2>    
            }
        ]
    ]
]
Run Code Online (Sandbox Code Playgroud)

我知道我可以索引两个或更多不同的字段,但我有强大的辅助内存约束,我不能索引相同的信息N次.

谢谢

小智 10

如果还没有,首先需要将自定义分析器映射到索引设置端点.

注意:如果索引存在且正在运行,请确保先关闭它.

POST /my_index/_close

然后将自定义分析器映射到设置端点.

PUT /my_index/_settings
{
  "settings": {
    "analysis": {
      "analyzer": {
        "custom_analyzer1": { 
          "type": "standard",
          "stopwords_path": "stopwords/stopwords.txt"
        },
        "custom_analyzer2": { 
          "type": "standard",
          "stopwords": ["stop", "words"]
        }
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

再次打开索引.

POST /my_index/_open

现在,您可以使用新的分析器查询索引.

GET /my_index/_search
{
  "query": {
    "bool": {
      "should": [{
        "match": {
          "field_1": {
            "query": "Hello world",
            "analyzer": "custom_analyzer1"
          }
        }
      }],
      "must": [{
        "match": {
          "field_2": {
            "query": "Stop words can be tough",
            "analyzer": "custom_analyzer2"
          }
        }
      }]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)