【问题标题】:How to sort return result of Elasticsearch如何对 Elasticsearch 的返回结果进行排序
【发布时间】:2021-10-21 10:14:36
【问题描述】:

我是 Elasticsearch 的新手。

我应该如何修改以下代码以使返回结果按“lastpost”时间降序排列?

我是否应该在“正文”中的“查询”下方添加“排序”

@app.route('/')
def index():
    return render_template('index.html')


@app.route('/search')
def analyzer():
    bc = BertClient(ip='bertserving', output_fmt='list')
    client = Elasticsearch('elasticsearch:9200')

    query = request.args.get('q')
    query_vector = bc.encode([query])[0]

    script_query = {
        "script_score": {
            "query": {"match_all": {}},
            "script": {
                "source": "cosineSimilarity(params.query_vector, doc['text_vector']) + 1.0",
                "params": {"query_vector": query_vector}
            }
        }
    }

    response = client.search(
        index=INDEX_NAME,
        body={
            "size": SEARCH_SIZE,
            "query": script_query,
            "_source": {"includes": ["title", "id","lastpost"]}
        }
    )
    print(query)
    pprint(response)
    return jsonify(response)


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

【问题讨论】:

  • 是的,这就是我要放的地方。 "sort" : { "lastpost": "desc" }

标签: python elasticsearch


【解决方案1】:

在 Body json 中添加排序,如下所示:

body={
        "size": SEARCH_SIZE,
        "sort": {"lastpost": {"order": "desc"}},
        "query": script_query,
        "_source": {"includes": ["title", "id","lastpost"]}
    }

如果你想对多个字段应用排序,那么你也可以将排序参数作为数组传递:

body={
        "size": SEARCH_SIZE,
        "sort": [{"lastpost": {"order": "desc"}}],
        "query": script_query,
        "_source": {"includes": ["title", "id","lastpost"]}
    }

【讨论】:

    【解决方案2】:

    是的!我将代码编辑为:

    body={
            "size": SEARCH_SIZE,
            "sort": [{"lastpost": {"order": "desc"}}],
            "query": script_query,
            "_source": {"includes": ["title", "id","lastpost"]}
        }
    

    但仍然有错误。然后我发现这是因为我创建索引时,格式不匹配,我没有涉及“lastpost”。所以我编辑了我的 index.json:

    {
      "settings": {
        "number_of_shards": 2,
        "number_of_replicas": 1
      },
      "mappings": {
        "dynamic": "true",
        "_source": {
          "enabled": "true"
        },
        "properties": {
          "title": {
            "type": "text"
          },
          "lastpost": {
            "type": "integer"
          },
          "text_vector": {
            "type": "dense_vector",
            "dims": 768
          }
        }
      }
    

    现在一切都很好!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 2018-07-09
      • 1970-01-01
      • 2019-04-02
      • 2016-05-21
      • 1970-01-01
      • 2019-07-12
      相关资源
      最近更新 更多