高级弹性搜索查询

Advanced elasticsearch query

我正在使用 laravel 4.2、mongodb 和 elasticsearch。下面是一个工作代码,我正在尝试将这个高级查询转换为 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();      

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

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

                        ]                       
                    ]   
                ]               
            ];

你能告诉我如何在 elasticsearch 中实现我上面第一次描述的相同查询吗?我想 return discontinued 产品 inventory,然后 return 产品 not equal to discontinued.

您描述的 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 现在应该很简单了。试一试。