Elasticsearch aggregate function error on laravel

- 1 answer

Ad

Elasticsearch gives error when integrating with laravel using aggregations. This is my code:

        $laws_y = Law::searchByQuery([
            'multi_match' => [
                'query' => $years,
                'fields' => ["law_year"]
            ],
            "aggs" => [
                "group_by_law_year" => ["terms" => ['field' => ["law_year"]]]
            ]
        ]);

I get following error:

BadRequest400Exception in GuzzleConnection.php line 277: {"error":{"root_cause":[{"type":"parse_exception","reason":"failed to parse search source. expected field name but got [START_OBJECT]"}],"type":"search_phase_execution_exception","reason":"all shards failed","phase":"query","grouped":true,"failed_shards":[{"shard":0,"index":"default","node":"BcRQOVhkS1SwTlvYPCEfHg","reason":{"type":"parse_exception","reason":"failed to parse search source. expected field name but got [START_OBJECT]"}}]},"status":400}

Does anyone know the solution?

Ad

Answer

Ad

From the Elasticquent documentation, the searchByQuery function takes the following parameters (see source here):

  • query - Your ElasticSearch Query
  • aggregations - The Aggregations you wish to return.
  • sourceFields - Limits returned set to the selected fields only
  • limit - Number of records to return
  • offset - Sets the record offset (use for paging results)
  • sort - Your sort query

In your call, you need to separate the query (first parameter) from the aggregations (second parameter). Do it like this instead:

     $laws_y = Law::searchByQuery([
        'multi_match' => [
            'query' => $years,
            'fields' => ["law_year"]
        ]
     ],
     [
        "group_by_law_year" => ["terms" => ['field' => "law_year"]]
     ]);
Ad
source: stackoverflow.com
Ad