如何结合bool必须和弹性搜索排序

时间:2015-08-28 07:01:27

标签: php sorting elasticsearch

我正在尝试对一些数据进行排序,在我的基础骨架中我的排序不起作用,如果我删除排序它工作正常。

那么我怎样才能将排序放在我的基础骨架中并对一些数据进行排序。

我不能放

   $params['body'] = [           
    'sort' => [['title' => ['order' => 'asc']]]];
$results = $client->search($params);

因为我有其他条件,我需要必须条件。 任何人都可以知道它是如何解决的。

任何建议都会非常感激。

      // my base skeleton          
      $params = array(
                'index' => "myIndex",
                'type' => "myType",
                'body' => array(
                    'query' => array(
                        'bool' => array(
                            'must' => array(
                            // empty should clause for starters
                            )
                        )
                    ),
                'sort' => array()
                )
            );

     // sorting is not working with bool and must
     if ($request->request->get('salarySort')) {
                $params['body']['query']['bool']['must'][] = array(
                    'sort' => array(
                        "title" => array('order' => 'asc')
                    )
                );
            }

这是我作为json_encode ---

得到的
{
  "took": 4,
  "timed_out": false,
  "_shards": {
    "total": 2,
    "successful": 1,
    "failed": 0
  },
  "hits": {
    "total": 1066,
    "max_score": null,
    "hits": [
      {
        "_index": "myIndex",
        "_type": "myType",
        "_id": "pe065319de73937aa6ef46413afd7aac26a58a611",
        "_score": null,
        "_source": {
          "title": "Smarason trycker ",
          "content": "HIF gör 2-0 mot Halmstad.",
          "tag": [
            "Soprts"
          ],
          "category": [
            "Sports"
          ]
        },
        "sort": [
          "0"
        ]
      },
      {
        "_index": "myIndex",
        "_type": "myType",
        "_id": "pebc44a70008f53f74f23ab23f8a1f79b2b729448",
        "_score": null,
        "_source": {
          "title": "Anders Svenssons tips gav 1-0",
          "content": "Anders Svenssons tips i halvtid Kalmar FF.",
          "source": "Unknown",
          "tag": [
            "Soprts"
          ],
          "category": [
            "Sports"
          ]
        },
        "sort": [
          "0"
        ]
      }
    ]
  }
}

在JSON中查询---

{
  "index": "myIndex",
  "type": "myType",
  "size": 30,
  "body": {
    "query": {
      "match_all": []
    },
    "sort": [
      {
        "title": "asc"
      }
    ]
  }
}

1 个答案:

答案 0 :(得分:1)

你几乎就在那里。您已将空sort数组正确放置在与query相同的级别,这是正确的。

如果您尝试将其作为bool/must约束而不是空sort数组中提供,则会出现此问题。

 // sorting is not working with bool and must
 if ($request->request->get('salarySort')) {
    $params['body']['sort'][] = array(      <---- this line needs to be changed
        "Salary" => 'asc'                   <---- this line needs to be changed, too
    );
 }
相关问题