Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FOS Elastica -- getting string representation of query

I am unit-testing a repository that uses FOS Elastica and I was wondering if anyone knows how to get the string version of a query, rather than in array form. Here is my repository method:

    /**
     * Creates query object by either first or last name, with given parameters
     *
     * @param $name
     *
     * @param array $params
     *
     * @return Query
     */
    public function findByFirstOrLast($name, array $params)
    {
        $queryString = new QueryString();
        $queryString->setQuery($name);
        $queryString->setFields(array('firstName', 'lastName'));


        $query = new Query();
        $query->setQuery($queryString);
        $query->setSort(array($params['sort'] => array('order' => $params['direction'])));

        return $query;
    }

Assuming $name = 'foo'; (and that I am sorting on id), I believe the corresponding FOS Elastica query should be

{
    "query":
    {
        "query_string":
            {
                "query":
                    "foo",
                    "fields":["firstName","lastName"]
            }
    },
    "sort":
    {
      "id":
          {
              "order":"asc"
          }
    }
}

Does anyone know how to get this json-string representation of the query? It doesn't necessarily have to be in this pretty format either, it can be a one-line string.

like image 954
DIMMSum Avatar asked Feb 24 '14 21:02

DIMMSum


2 Answers

I see you no longer are using this but I ended up needing the same thing.

Right before return $query you can use json_encode($query->getQuery()->toArray()) and that should give you what you need as a single line string.

like image 181
SidewaysGravity Avatar answered Sep 28 '22 07:09

SidewaysGravity


Not a direct answer to the question but very related. When using a tool like found.no to test your elasticsearch queries, it can be interesting to have the output as YAML so you can paste in the found.no editor like this:

query:
    filtered:
    query:
        multi_match:
            query: php
            operator: AND
            fields:
                - field1^30
                - field2
                - field3                    
                - _all

You can have this kind of output with the following function:

use Elastica\Query;
use Symfony\Component\Yaml\Dumper;

/**
 * @param Query $query
 * @param bool  $asYaml
 */
protected function debugQuery(Query $query, $asYaml = false)
{
    echo '<pre>';
    $debug = ['query' => $query->getQuery()->toArray()];

    if (false === $asYaml) {
        echo json_encode($debug, JSON_PRETTY_PRINT);
        die();
    }

    $dumper = new Dumper();
    $yaml = $dumper->dump($debug, 100);

    echo $yaml;
    die();
}

So you can choose either format.

like image 30
COil Avatar answered Sep 28 '22 08:09

COil