Elastica:如何进行过滤查询

时间:2016-04-03 17:46:22

标签: php elasticsearch elastica

我正在尝试实现GROUP BY categories_slug,WHERE location_country =' CA'和location_province =' ON'在ElasticSearch中

{
  "aggs": {
    "categories": {
      "terms": {
        "field": "categories.slug",
        "order": {
          "_term": "asc"
        },
        "size": 1000
      }
    }
  },
  "query": {
    "filtered": {
      "filter": [
        {
          "term": {
            "locations.country": "CA"
          }
        },
        {
          "term": {
            "locations.administrative_area_level_1": "QC"
          }
        }
      ]
    }
  }
}

如何使用elastica来实现此查询?

1 个答案:

答案 0 :(得分:0)

经过反复试验,这是怎么做的。

    //Aggregation Terms
    $termsAgg = new \Elastica\Aggregation\Terms("categories");
    $termsAgg->setField("categories.slug");
    $termsAgg->setOrder("_term", "asc");
    $termsAgg->setSize(1000);

    //Boolean Filter
    $boolFilter = new \Elastica\Filter\BoolFilter();
    foreach ($this->locationSearchFilter as $key => $value) {
        $boolFilter->addMust(new \Elastica\Filter\Term([$key => $value]));
    }

    //Filter
    $filter  = new \Elastica\Query\Filtered();
    $filter->setFilter($boolFilter);

    //Client
    $client = new \Elastica\Client([
        'connections' => [
            array('host' => 'localhost', 'port' => 9200),
        ],
    ]);

    //Search
    $search = new \Elastica\Search($client);
    $search->addType('yourType');
    $search->addIndex('yourIndex');

    //Query
    $query = new \Elastica\Query();
    $query->addAggregation($termsAgg);
    $query->setQuery($filter);