按名称弹性搜索排序

时间:2016-10-01 14:24:34

标签: php elasticsearch

我尝试使用弹性搜索&amp ;,按名称对文档进行排序。官方的php客户端,我该怎么办?

    $params = [
        'index' => $this->index ,
        'type' => 'videos',
        'from' => $this->uri->segment(2),
        'size' => 12,
        'body' => [
        'query' => [
        'filtered' => [
            'filter' => [
                'term' => [ 'name' => $query ] ,
                'term' => [ 'tags' => $query ]
              ]
           ]
        ]
      ]
    ];




    $data['results'] = $this->client->search($params);

4 个答案:

答案 0 :(得分:1)

我知道这个问题已经超过一年了,但在互联网上找不到答案,所以无论如何我都会回答。
要指定要排序的字段和要排序的顺序,请使用以下语法:

$params['sort'] = array('updated_at:desc');

要对多个字段进行排序:

$params['sort'] = array('updated_at:desc', 'user_id:asc', ...);

答案 1 :(得分:0)

试试这个

$params = [
        'index' => $this->index ,
        'type' => 'videos',
        'from' => $this->uri->segment(2),
        'size' => 12,
        'body' => [
        'query' => [
        'filtered' => [
            'filter' => [
                'term' => [ 'name' => $query ] ,
                'term' => [ 'tags' => $query ]
              ]
           ]
        ],
        'sort' => [
            'name' => [
                'order' => 'asc'
            ]
        ]
      ]
    ];

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html

答案 2 :(得分:0)

如果您未分析keyword,则必须在不启用字段数据的情况下使用它:

$params = [
        'index' => $this->index ,
        'type' => 'videos',
        'from' => $this->uri->segment(2),
        'size' => 12,
        'body' => [
        'query' => [
        'filtered' => [
            'filter' => [
                'term' => [ 'name' => $query ] ,
                'term' => [ 'tags' => $query ]
              ]
           ]
        ],
        'sort' => [
            'name' => [
                'order.keyword' => 'asc'
            ]
        ]
      ]
    ];

但是,如果您没有未分析的关键字,则应重置索引映射以将fielddata启用为name字段:

    curl -X PUT "localhost:9200/my_index/_mapping" -H 'Content-Type: application/json' -d'
    {
      "properties": {
        "name": { 
          "type":     "text",
          "fielddata": true
        }
      }
    }

'

请参阅:https://www.elastic.co/guide/en/elasticsearch/reference/current/fielddata.html

答案 3 :(得分:0)

我只是在寻找同一个问题的答案时看到了这篇文章,就我而言,解决方案比我在这里看到的要简单得多且与众不同。

$params['body']['sort'] = [ 'id' => 'desc']

使用"elasticsearch/elasticsearch": "^6.1"

对我来说效果很好