Search code examples
phpelasticsearchsymfony-2.8foselasticabundle

FOSElastica nested query


My collections are like this:

  {
    "_index" : "test_index",
    "_type" : "test_type",
    "_id" : "10000",
    "_score" : 1.0,
    "_source" : {
      "user_id" : 12,
      "index_date" : {
        "date" : "2018-02-06 14:25:49.816952",
        "timezone_type" : 3,
        "timezone" : "UTC"
      },
      "rating" : null,
      "orders" : [          
        {
          "hour" : "08",
          "count" : 1
        },
        {
          "hour" : "10",
          "count" : 1
        }
      ],
      "products" : [
        {
          "p_id" : 970111,
          "count" : 4
        },
        {
          "p_id" : 1280811,
          "count" : 1
        },

      ]
    }
  },

and tried to access to {"hour":"10"}

My query is:

            $query = new Query\Nested();
            $query->setPath('orders');

            $term = new Term();
            $term->setTerm('orders.hour', $order->getCreatedAt()->format('H'));
            $query->setQuery($term);
            dump($finder->find($query));die;

but i got the following error:

  [Elastica\Exception\ResponseException]                           
  failed to create query: {                                        
    "nested" : {                                                   
      "query" : {                                                  
        "term" : {                                                 
          "orders.hour" : {                                        
            "value" : "12",                                        
            "boost" : 1.0                                          
          }                                                        
        }                                                          
      },                                                           
      "path" : "orders",                                           
      "ignore_unmapped" : false,                                   
      "score_mode" : "avg",                                        
      "boost" : 1.0                                                
    }                                                              
  } [index: test_index] [reason: all shards failed]  

Solution

  • Your documents not look like nested queries.

    I assume that finder is your repository manager that is defined as orders repository, your code should look something like this

    $finder = $this->get('fos_elastica.repository_manager')->getRepository('YourBundle:order');
    
    $boolquery = new Query\BoolQuery();
    
    $term = new Query\Term();
    $term->setTerm('hour', $order->getCreatedAt()->format('H'));
    
    $boolquery->addMust($term);
    
    $finder->find($boolquery);