如何在Elasticserch查询中获得3个随机搜索结果

时间:2019-03-22 10:56:37

标签: elasticsearch aws-elasticsearch

我有我的Elasticsearch查询,该查询返回的发布日期范围之间的记录:

{
  query : {
    bool: {
      filter: [

      ],
      must: {
        range: {
          publishedDate: {
            gte: "2018-11-01",
            lte: "2019-03-30"
          }
        }
      }
    }
  }
  from: 0,
  size: 3,
}

每次发送此查询时,我需要显示3个随机结果

elastic search documentation中提到,我可以发送种子以获得随机结果:

遵循文档之后,我将查询更新为:

{
  "query" : {
    "bool": {
      "filter": [

      ],
      "must": {
        "range": {
          "publishedDate": {
            "gte": "2018-11-01",
            "lte": "2019-03-30"
          }
        }
      }
    },
    "function_score": {
      "functions": [
        {
          "random_score": {
            "seed": "123123123"
           }
        }
      ]
    }
  },
  "from": 0,
  "size": 3
}

但是它不起作用(说查询格式不正确),任何人都可以建议如何更正此查询以返回3个随机搜索结果。

1 个答案:

答案 0 :(得分:1)

如果您只需要返回随机结果,则可以将查询的结构重组为类似于以下内容

{
  "query": {
    "function_score": {
      "query": {
        "range": {
          "publishedDate": {
            "gte": "2018-11-01",
            "lte": "2019-03-30"
          }
        }
      },
      "boost": "5",
      "random_score": {},
      "boost_mode": "multiply"
    }
  },
  "from": 0,
  "size": 3
}

从弹性文档中修改- https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html