Search code examples
phpsymfonyelasticsearchfoselasticabundle

FosElasticaBundle Query Prefix does not seem to return corrent results


What I'm trying to accomplish is to return results that:

  • search in 2 types ( recipe, product ), for a moment didn't take care of it
  • property name starts with search query
  • establish fieldFuzziness ( to search with typos )

So far I have Controller:

$q = 'pom'; // search string

/** @var FinderInterface $finder */
$finder = $this->container->get('fos_elastica.finder.app.recipe');

$match = new Match();
$match
    ->setFieldQuery('name', $q)
    ->setFieldFuzziness('name', 2.5)
;

$prefix = new Query\Prefix();
$prefix
    ->setPrefix('name', $q)
;

$bool = new Query\BoolQuery();
$bool
    ->addMust($prefix)
    ->addShould($match);

$results = $finder->find($bool);

Example data:

+----+------------------------------------+-------------+
| id |                name                | otherFields |
+----+------------------------------------+-------------+
|  1 | Coctail pomegranate                |             |
|  2 | Coctail pomegranate with nuts      |             |
|  3 | Coctail pomegranate with mushrooms |             |
+----+------------------------------------+-------------+

fos_elastica.yml

fos_elastica:
clients:
    default: { host: %elastic_host%, port: %elastic_port% }
indexes:
    app:
        client: default
        types:
            recipe:
                properties:
                    recipeId :
                        type : integer
                    recipeDescription :
                        type : text
                    createdAt :
                        type : date
                    updatedAt :
                        type : date
                    name :
                        type : text
                persistence:
                    identifier: recipeId
                    driver: orm
                    model: AppBundle\Entity\Recipe
                    finder: ~
                    provider: ~
                    listener: ~

The problem is Prefix defines, that field name must starts with 'pom', so it must get 0 results, but I get all three results from Example Data.


Solution

  • The prefix query applies to not analyzed fields. Check this Term level queries doc For what you are doing you should user a Match Phrase Prefix query Doc here

    This is the ES doc, so you must translate that queries to FosElastica queries or just create an array and use it as query.