yii2 + elasticsearch:如何使用' sort'使用'查询'正在搜索

时间:2018-06-06 07:41:27

标签: yii2

信息:使用" yiisoft / yii2-elasticsearch":" 2.1.x-dev"

我想使用yii2弹性执行以下操作: (来自https://www.elastic.co/guide/en/elasticsearch/reference/current/search-request-sort.html

{
    "sort" : [
      {
          "_geo_distance" : {
              "location" : {
                    "lat" : -33.936593,
                    "lon" : 18.4204544
              }, 
              "order" : "asc",
              "unit" : "km"
          }
      }
  ],
    "query": {
        "bool" : {
            "must" : {
                "match_all" : {}
            },
            "filter" : {
                "geo_distance" : {
                    "distance" : "3000km",
                    "location" : {
                        "lat" : -33.936593,
                        "lon" : 18.4204544
                    }
                }
            }
        }
    }
}

当我使用以下内容时:

$query = [
            'bool' => [
//                    'must' => [
//                        'match_all' => [] // this throws a diff error
//                    ],
                'filter' => [
                    'geo_distance' => [
                        'distance' => $distance . "km",
                        'location' => [
                            'lat' => $lat,
                            'lon' => $lng
                        ]
                    ]
                ]
            ]
        ];

        $sort = [
            'geo_distance' => [
                'location' => [
                    'lat' => $lat,
                    'lon' => $lng
                ],
                'order' => 'asc',
                'unit' => 'km'
            ]
        ];

        $models = Model::find()
            ->query($query)
            ->orderBy($sort)
            ->all();

我收到错误:

  

例外' yii \ elasticsearch \例外'使用消息' Elasticsearch   请求失败,代码为400.响应正文:   {"错误" {" ROOT_CAUSE":[{"类型":" illegal_argument_exception""理由":& #34; [field_sort]   未知字段[location],解析器没有   发现"}],"类型":" illegal_argument_exception""理由":" [field_sort]   未知字段[location],找不到解析器"}," status":400}'

也许我可以将原始json查询传递给yii2 elasticsearch?不确定yii2-elasticsearch lib是否能够处理'位置' (geo_distance)字段呢?

帮助表示感谢, gvanto

1 个答案:

答案 0 :(得分:0)

您可以使用orderBy方法并编写类似这样的内容

MyModel::find()
  ->query(...)
  ->orderBy([
    'post_date' => SORT_ASC,
    'name' => SORT_DESC
  ])
  ->all()