【问题标题】:Elastic search script sort text as Number弹性搜索脚本将文本排序为数字
【发布时间】:2022-10-24 05:38:35
【问题描述】:

我有一个弹性搜索字段ID,它是一个数字,但在索引中设置为“文本”。由于要重新加载大量数据,我无法更改索引。 我正在编写一个脚本来执行此排序,但出现“Bad_request”错误。

Script script = new Script(ScriptType.INLINE, "painless", "ctx._source.ID.keyword", Collections.emptyMap());
ScriptSortBuilder.ScriptSortType sortType = ScriptSortBuilder.ScriptSortType.NUMBER;
builder.sort(SortBuilders.scriptSort(script, sortType).order(SortOrder.DESC));

searchRequest.source(builder);
response = restsearchClient.search(searchRequest, RequestOptions.DEFAULT);

我尝试了以下 idorcode 值:doc['ID']doc['ID.keyword']ctx._source.IDctx._source.ID.keyword


请指教!

【问题讨论】:

  • 如果为 com ID 创建了关键字子字段,您可以检查您的映射吗?如果关键字子字段不存在,我看不到任何其他方法可以使用新映射重新索引索引。
  • 是的,创建了 Id.keyword
  • 你能显示你的查询吗?我知道您的代码在 java 中,但查看查询的生成方式很重要。既然你说映射有 ID.keyword 这样的排序应该工作:...“sort”:[ {“ID.keyword”:{“order”:“asc”}}]。

标签: sorting elasticsearch search


【解决方案1】:

如果我的理解正确,那么您想对在 Elasticsearch 中存储为字符串而不是整数的数字进行排序。

下面是示例 Elasticsearch 查询:

{
  "query": {
    "match_all": {}
  },
  "sort": {
    "_script": {
      "type": "Number",
      "order": "desc",
      "script": {
        "lang": "painless",
        "source": """
        String s = doc['ID.keyword'].value;
          int idvalue = Integer.parseInt(s);
          return idvalue;
        """
      }
    }
  }
}

下面是Java代码:

Script script = new Script(ScriptType.INLINE, "painless", "String s = doc['ID.keyword'].value;int idvalue = Integer.parseInt(s);return idvalue;", Collections.emptyMap());
ScriptSortBuilder.ScriptSortType sortType = ScriptSortBuilder.ScriptSortType.NUMBER;
builder.sort(SortBuilders.scriptSort(script, sortType).order(SortOrder.DESC));

【讨论】:

  • 非常感谢 Sagar,这有效...我不得不更改为“source”:“Long.parseLong(doc['ID.keyword'].value)”
  • @vens 很高兴知道它对您有帮助!您可以将答案标记为解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多