【问题标题】:Advanced elasticsearch query高级弹性搜索查询
【发布时间】:2016-03-27 02:23:57
【问题描述】:

我正在使用 laravel 4.2、mongodb 和 elasticsearch。下面是一个工作代码,我正在尝试将此高级 where 查询转换为 elasticsearch 查询:

$products = Product::where(function ($query) { 
            $query->where (function($subquery1){ 
                $subquery1->where('status', '=', 'discontinued')->where('inventory', '>', 0); 
                }); 
            $query->orWhere (function($subquery2){
                $subquery2->where('status', '<>', 'discontinued'); 
                });                         
        })->get();      

到目前为止,我所能得到的只是退回停产的产品,下面的代码有效,但这不是我需要的:

$must = [
               ['bool' => 
                    ['should' => 
                        ['term' => 
                            ['status' => 'discontinued']                            

                        ]                       
                    ]   
                ]               
            ];

你能告诉我如何在弹性搜索中实现我上面第一次描述的相同查询吗?我想用inventory 退货discontinued 产品,然后还退货not equal to discontinued 产品。

【问题讨论】:

    标签: mongodb laravel elasticsearch elasticsearch-plugin advanced-search


    【解决方案1】:

    您描述的 WHERE 查询可以这样用 SQL 表示

    ... WHERE (status = discontinued AND inventory > 0)
           OR status <> discontinued
    

    在 Elasticsearch Query DSL 中,可以这样表示:

    {
      "query": {
        "filtered": {
          "filter": {
            "bool": {
              "should": [
                {
                  "bool": {
                    "must": [
                      {
                        "term": {
                          "status": "discontinued"
                        }
                      },
                      {
                        "range": {
                          "inventory": {
                            "gt": 0
                          }
                        }
                      }
                    ]
                  }
                },
                {
                  "bool": {
                    "must_not": [
                      {
                        "term": {
                          "status": "discontinued"
                        }
                      }
                    ]
                  }
                }
              ]
            }
          }
        }
      }
    }
    

    现在将这个查询翻译成 PHP 应该很简单了。试试看吧。

    【讨论】:

    • 这很好用!谢谢。我已经工作了好几天来学习这个Query DSL。刚才我从你那里学到了一些东西。
    猜你喜欢
    • 1970-01-01
    • 2023-01-16
    • 2014-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-21
    • 2015-06-09
    相关资源
    最近更新 更多