dongyi1921 2016-08-15 18:20
浏览 512

如何在ElasticSearch中合并2个索引的结果?

I have 2 indices documents_1 and documents_2 in ElasticSearch with different mapping types (they have some different attributes). I am using Yii2 framework on php to search on web.

Question: How can I search over 2 indices (if it is possible) and merge results in one sorted by date for example? To explain I do need something like this:

$queryOne = DocumentOne::find()->all();
$queryTwo = DocumentTwo::find()->all();

merge_results($queryOne, $queryTwo);

DocumentOne.php

class DocumentOne extends \yii\elasticsearch\ActiveRecord
{
    public static function index()
    {
        return 'documents_1';
    }

    public static function type()
    {
        return 'type_a';
    }

    public function attributes()
    {
        return ['id', 'any_1', 'created_format_1'];
    }
}

DocumentTwo.php

class DocumentTwo extends \yii\elasticsearch\ActiveRecord
{
    public static function index()
    {
        return 'documents_2';
    }

    public static function type()
    {
        return 'type_b';
    }

    public function attributes()
    {
        return ['id', 'any_2', 'created_format_2'];
    }
}

DocumentOneSearch.php

class DocumentOneSearch extends DocumentOne
{
    public function search($params)
    {
        $query = DocumentOne::find();
        $sort = new Sort([
            'defaultOrder' => [
                'created_format_1' => SORT_DESC,
            ],
        ]);

        return $query
            ->orderBy($sort->orders)
            ->all();
    }
}
  • 写回答

1条回答 默认 最新

  • dongxing5525 2016-08-16 19:57
    关注

    Have you considered something like:

    function cmp($a, $b)
    {
        return strcmp($a->date, $b->date);
    }
    
    $queryOne = DocumentOne::find()->all();
    $queryTwo = DocumentTwo::find()->all();
    
    $result = array_merge($queryOne, $queryTwo);
    
    usort($result, "cmp");
    

    assuming that your documents have a property named date?

    edit: If you only needs the first set of results to be sorted, then you could just array_merge() the results

    评论

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!