Tejas Sateesh
Tejas Sateesh

Reputation: 74

Using "terms" and "range" filters together in Elasticsearch

I searched everywhere, but none of the answers met my requirements. My code goes something like this:

File 1

<?php
 if($year != 0)
 {
 $temp = strval($year);
 $term =[ 
         "range" => [
           "decidedon" => [
               "gte" => $temp."-01-01",
               "lte" => $temp."-12-31"
                      ]
                    ]
        ];
 array_push($params['body']['query']['filtered']['filter']['bool']['must'], $term);
 }

File 2

<?php
 $dummy = explode(" ",$cor);
 $params['body']['query']['filtered']['filter']['bool']['must'] = ['terms'=> ['court' => $dummy]  ];

I include them in my index page at different instances, as follows

if(isset($_GET['cor'])){
 $cor = $_GET['cor'];
 if(strcasecmp($cor,"all")!=0){
  include 'courtfilter.php';  
  }
}

if(isset($_GET['year'])){
 $year = $_GET['year'];
 if($year != 0){
  include 'yearfilter.php';
  }
} 

When I run a query, it says terms and range cannot be nested together. Can someone tell me a better way to do this without complicating my program or without having to write a separate filter for these two?

(I am a beginner, Please pardon me if I am wrong or if this is too trivial.)

Upvotes: 2

Views: 148

Answers (1)

Val
Val

Reputation: 217584

You're almost there. In your second file, you need to insert the terms into your must like this:

$params['body']['query']['filtered']['filter']['bool']['must'] = [['terms'=> ['court' => $dummy]  ]];
                                                                 ^                                 ^
                                                                 |                                 |
                                                               add this .....................and this

i.e. the bool/must must be an array and you were assigning it an object/hash directly.

A better way would be to initialize the must clause before including any of the files (i.e. before if(isset($_GET['cor']))). You would first initialize your bool/must array like this:

$params['body']['query']['filtered']['filter']['bool']['must'] = [];

And then in both of your included files, you can simply do an array_push() like you do in the file yearfilter.php

Upvotes: 1

Related Questions