【问题标题】:yii2 + elasticsearch: How to use 'sort' with 'query' in searchyii2 + elasticsearch:如何在搜索中使用“排序”和“查询”
【发布时间】:2018-06-08 17:29:36
【问题描述】:

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

我想使用 yii2 elastic 执行以下操作: (来自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\Exception' 带有消息 'Elasticsearch 请求失败,代码为 400。响应正文: {"error":{"root_cause":[{"type":"illegal_argument_exception","re​​ason":"[field_sort] 未知字段 [位置],解析器不是 找到"}],"type":"illegal_argument_exception","re​​ason":"[field_sort] 未知字段 [位置],未找到解析器"},"status":400}'

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

帮助表示赞赏, 万托

【问题讨论】:

    标签: yii2


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢弗拉基米尔试过这个,不工作......我最终用 guzzle 进行了纯 curl 调用......
    猜你喜欢
    • 2022-12-20
    • 2015-02-14
    • 2019-12-19
    • 1970-01-01
    • 2022-08-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多