java - Elastic Search - 排序 - 在 0 条件下在整数字段之间切换

标签 java indexing lucene elasticsearch

假设我有两个双数据类型字段,分别称为priority1 和priority2。 我们需要对priority1进行排序,但是当priority1为0时则选择priority2字段。

示例 -

Document 1 - priority1 : 8.5, priority2 : 9.0
Document 2 - priority1 : 5.5, priority2 : 6.0
Document 3 - priority1 : 0, priority2 : 9.0
Document 4 - priority1 : 8.0, priority2 : 8.5
Document 5 - priority1 : 0, priority2 : 7.5

文件应按顺序排序 -

Document 2  (5.5)
Document 5  (7.5)
Document 4  (8.0)
Document 1  (8.5)
Document 3  (9.0)

最佳答案

您可以使用 custom score 来实现此目的脚本。

以下请求:

POST test/scores/_search
{
  "sort":{
    "_script":{
      "lang":"groovy",
      "script" : "doc['priority1'].value == 0 ? doc['priority2'].value : doc['priority1'].value",
      "type" : "number",
      "order" : "asc"
    }
  }
}

会给你你想要的订单:

hits": [
         {
            "_index": "test",
            "_type": "scores",
            "_id": "7uyu0prrT-SCJFvwSVUI0Q",
            "_score": null,
            "_source": {
               "p1": 5.5,
               "p2": 6
            },
            "sort": [
               5.5
            ]
         },
         {
            "_index": "test",
            "_type": "scores",
            "_id": "mRjUlMHvQ4-Dj-BKVL1Oyg",
            "_score": null,
            "_source": {
               "p1": 0,
               "p2": 7.5
            },
            "sort": [
               7.5
            ]
         },
         {
            "_index": "test",
            "_type": "scores",
            "_id": "QKCK2G9GT0y6FzwAvu5p5A",
            "_score": null,
            "_source": {
               "p1": 8,
               "p2": 8.5
            },
            "sort": [
               8
            ]
         },
         {
            "_index": "test",
            "_type": "scores",
            "_id": "4-kUu3gDSTON9F6bd3ieRw",
            "_score": null,
            "_source": {
               "p1": 8.5,
               "p2": 9
            },
            "sort": [
               8.5
            ]
         },
         {
            "_index": "test",
            "_type": "scores",
            "_id": "KOqf6bhrTK2JioRFEppcjw",
            "_score": null,
            "_source": {
               "p1": 0,
               "p2": 9
            },
            "sort": [
               9
            ]
         }
      ]

直接使用 function_score 查询(此处为 documentation)并在查询中重复使用相同的脚本可以获得更好的性能。

关于java - Elastic Search - 排序 - 在 0 条件下在整数字段之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26054554/

相关文章:

java - Lucene索引: getting empty result while query

elasticsearch - 尝试从Elasticsearch提取叶字段

solr - 避免系统文件夹的 Sitecore Lucene/Solr 索引

Java JDBC MySQL异常: “Operation not allowed after ResultSet closed”

java - 如何使用 ksoap 2 对 Web 服务调用强制执行超时?

java - 如何在树查看器中隐藏具有树层次结构的第一列?

linq - LINQ2SQL 是否使用表索引?

java - 使用 GridBagLayout JTables 和 JScrollPane 不起作用

MongoDB 复合索引优化键和范围条件更新

java - JVM 在 lucene 索引期间连续崩溃