【问题标题】:How to order on a field based on how far to the left it occurs in Elasticsearch?如何根据在 Elasticsearch 中出现在左侧的距离对字段进行排序?
【发布时间】:2019-06-28 11:12:17
【问题描述】:

我正在尝试使用 Elasticsearch Java API 搜索具有包含搜索词的字段的文档,然后根据该词在字段值中出现的距离对结果进行排序。

这就是我创建索引的方式:

final CreateIndexRequest request = new CreateIndexRequest("index-name");
request.settings(Settings.builder().put("index.max_result_window", MAX_RESULTS));
client.admin().indices().create(request).actionGet();

这就是我创建映射的方式:

{
  "part": {
    "properties":{
      "PartNumber":{
        "type":"keyword"
      }
    }
  }
}

这就是我查询 Elasticsearch 的方式:

final CreateIndexRequest request = new CreateIndexRequest("index-name");
request.settings(Settings.builder().put("index.max_result_window", MAX_RESULTS));
client.admin().indices().create(request).actionGet();
client.admin()
      .indices()
      .preparePutMapping("index-name")
      .setType("part")
      .setSource(source, XContentType.JSON).execute().actionGet();

final SearchResponse searchResponse = elasticClient.getClient()
                .prepareSearch("index-name")
                .setQuery(boolQuery().must(wildcardQuery("PartNumber", "*five*")))
                .addSort("PartNumber", SortOrder.DESC)
                .setTypes("part")
                .get();

按以下顺序返回结果:

three five six four five four 11
five 11 three 2 three five four threefive
11 22 three fourfive five four
1 22 three four six five

但是,我希望它们的顺序是:

five 11 three 2 three five four threefive
three five six four five four 11
11 22 three fourfive five four
1 22 three four six five

它根据术语five 出现在值的左侧多远对它们进行排序,这可能吗?

【问题讨论】:

    标签: java elasticsearch


    【解决方案1】:

    首先,尽量不要使用wildcard查询。它们效率不高,尤其是当您使用带有长文本的 keyword 字段时。

    如果您使用通配符查询来匹配文本fourfive 中的five,您应该使用ngram tokenizer。

    也就是说,计算分数时不考虑标记的位置。考虑到令牌的位置,据我所知没有简单的方法来排序文档。

    一种解决方案可能是使用多个 span_first 查询包装在带有不同 end 参数的应该查询中。然后,出现在第一个位置的令牌将匹配比出现在第二个位置的更多查询,等等。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-14
      • 1970-01-01
      • 2013-04-11
      • 2013-02-26
      相关资源
      最近更新 更多