You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Elasticsearch搜索时能否直接在响应中返回search tokens数组

Elasticsearch 目前没有原生配置项可以直接在搜索响应中返回独立的搜索分词数组,但有两种可行方案可以在单次查询内实现需求,无需额外发起analyze请求:

  • 方案1:使用脚本字段直接在查询侧生成分词结果
    你可以在查询体中加入script_fields配置,通过Painless脚本调用索引对应的分析器直接对查询语句分词,完整查询示例如下:
{
   "explain": true,
   "query" : {
      "query_string" : {
          "query": "\"General Electric\""
      },
      "default_field": "all"
   },
   "script_fields": {
      "search_tokens": {
        "script": {
          "lang": "painless",
          "source": """
            import java.io.ByteArrayInputStream;
            import java.io.InputStream;
            import java.io.IOException;
            import org.apache.lucene.analysis.Analyzer;
            import org.apache.lucene.analysis.TokenStream;
            import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
            import java.nio.charset.StandardCharsets;

            def tokens = new ArrayList();
            // 替换为你的all字段对应的分析器名称
            Analyzer analyzer = ctx.getIndexSettings().getAnalyzer("your_analyzer_name");
            try (InputStream stream = new ByteArrayInputStream(params.query_str.getBytes(StandardCharsets.UTF_8));
                TokenStream tokenStream = analyzer.tokenStream("all", stream)) {
                  CharTermAttribute attr = tokenStream.addAttribute(CharTermAttribute.class);
                  tokenStream.reset();
                  while (tokenStream.incrementToken()) {
                    tokens.add(attr.toString());
                  }
                  tokenStream.end();
            } catch (IOException e) {
              // 可根据需要添加异常处理逻辑
            }
            return tokens;
          """,
          "params": {
            "query_str": "\"General Electric\""
          }
        }
      }
   }
}

配置完成后,每个返回的命中结果中都会新增search_tokens字段,值就是你需要的分词数组,格式为["gener", "electr"]。

  • 方案2:解析现有explain返回结果提取分词
    如果你已经开启了explain: true,可以直接通过固定规则提取分词:explain的details层级下第一个weight描述语句里,双引号包裹的内容就是分词后的短语,按空格拆分即可得到分词数组,只需要写简单的字符串匹配逻辑即可完成,性能开销极低。

内容的提问来源于stack exchange,提问作者Evgeni Nabokov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 13:21:02