首页 > 解决方案 > 尝试有条件地实现 ElasticSearch 排序

问题描述

这是我的映射:-

{
  "test": {
    "aliases": {
      
    },
    "mappings": {
      "courses": {
        "properties": {
          "is_sponsored": {
            "type": "long"
          },
          "sponsored_end_date": {
            "type": "date",
            "format": "yyyy-MM-dd HH:mm:ss"
          },
          "sponsored_start_date": {
            "type": "date",
            "format": "yyyy-MM-dd HH:mm:ss"
          },
          "settings": {
            "index": {
              "creation_date": "1609945591003",
              "number_of_shards": "5",
              "number_of_replicas": "1",
              "uuid": "3S6mwaIbSFuTKPtuj8sSWw",
              "version": {
                "created": "6070199"
              },
              "provided_name": "test"
            }
          }
        }
      }
    }
  }
}

我想在顶部显示那些“is_spired”值为真且当前日期介于“赞助开始日期”和“赞助结束日期”之间的课程。一旦“赞助结束日期”通过,它应该显示在正常位置。我是 ElasticSearch 的新手,所以请建议一种方法来做到这一点。我正在使用 php。

谢谢

标签: phplaravelelasticsearch

解决方案


您可以使用function_score来提升某些文档

询问

{
  "query": {
    "function_score": {
      "query": {
        "match_all": {}
      },
      "functions": [
        {
          "filter": {
            "bool": {
              "must": [
                {
                  "term": {
                    "is_sponsored": 1
                  }
                },
                {
                  "range": {
                    "sponsored_start_date": {
                      "lte": "now"
                    }
                  }
                },
                {
                  "range": {
                    "sponsored_end_date": {
                      "gte": "now"
                    }
                  }
                }
              ]
            }
          },
          "weight": 10
        }
      ],
      "score_mode": "sum"
    }
  }
}

结果

    "hits" : [
      {
        "_index" : "index45",
        "_type" : "_doc",
        "_id" : "sdb6L3wBJ0n9LhX2J02r",
        "_score" : 10.0,
        "_source" : {
          "is_sponsored" : 1,
          "sponsored_start_date" : "2021-09-01",
          "sponsored_end_date" : "2021-09-30"
        }
      },
      {
        "_index" : "index45",
        "_type" : "_doc",
        "_id" : "stb6L3wBJ0n9LhX2PE0c",
        "_score" : 1.0,
        "_source" : {
          "is_sponsored" : 0,
          "sponsored_start_date" : "2021-09-01",
          "sponsored_end_date" : "2021-09-30"
        }
      },
      {
        "_index" : "index45",
        "_type" : "_doc",
        "_id" : "s9b6L3wBJ0n9LhX2Z00v",
        "_score" : 1.0,
        "_source" : {
          "is_sponsored" : 1,
          "sponsored_start_date" : "2021-10-01",
          "sponsored_end_date" : "2021-10-30"
        }
      }
    ]

满足所有三个条件的文档将获得更高的权重。其余文件将有正常评分。


推荐阅读