Fastest Way to Search with Symfony2 and Elastica

Fastest Way to Search with Symfony2 and Elastica.

Method 1

Installing Elasticasearch on window platform and integrate FOSElastica bundle into Symfony framework also linking elasticasearch index and doctrine model with easy steps.

In this post we will learn how to use symfony and elastica search to get fastest search result and how to integrate elastica search into symfony framework. We will also focus on how to setup elastica server into you local or remote machine and how to fire search query using symfony and how to get result.

What is Elastica search?

Elastica search is open source search engine built top on Apache Lucene. Its a full text search engine library. Lucene is high performance and fully featured search engine library in existence today both open source and proprietary.

Installing Elastica search

To installing elastica search first you need Java. Preferably, you should install the latest version from the Java official site. Elastica search required at leash Java 7. After installing the latest version of java set the jdk path to the JAVA_HOME variable

JAVA_HOME = C:\Program Files\Java\jdk1.8.0_60

Now you can download the latest version of Elastic search from elasticsearch.org/download. Windows users can configure Elasticsearch to run as a service to run in the background or start automatically at startup without any user interaction. This can be achieved through service.bat script under bin/ folder which allows one to install, remove, manage or configure the service and potentially start and stop the service, all from the command-line.

c:\elasticsearch-1.3.9\bin>service
Usage: service.bat install|remove|start|stop|manager [SERVICE_ID]

The information is made during installing elastic search:

c:\elasticsearch-1.3.9\bin>service install
Installing service      :  "elasticsearch-service-x64"
Using JAVA_HOME (64-bit):  "c:\jvm\jdk1.7"
The service 'elasticsearch-service-x64' has been installed.

Method 2

To integrate Elastica search into symfony we will use FOSElastica bundle. So to use FOSElastica search bundle we follow some basic steps:

Download FOSElastica bundle via composer

Add below line to command prompt. This will automatically download the bundle.

$ composer require friendsofsymfony/elastica-bundle

Enable FOSElastica bundle

After downloading bundle you need to enable the bundle for your symfony app. Enable the bundle by adding the following line in the app/AppKernel.php file of your project:



<?php
// app/AppKernel.php

// ...
class AppKernel extends Kernel
{
public function registerBundles()
{
$bundles = array(
// ...
new FOS\ElasticaBundle\FOSElasticaBundle(),
);

// ...
}
}

Elastica basic configuration

FOSElastica bundle can easily set up or configure via some easy configuration. In most cases, every app required only one elastic search index. In below configuration we provide some basic configuration, In this configuration, ‘mysite’ is an elastic search index and all the title, description, tags, keywords are the table fields which are associated with Post table.


fos_elastica:
    clients:
        default: { host: localhost, port: 9200 }
    indexes:
        mysite:
            types:
                post:		
                    mappings:
                        title : { type: string, boost: 5 }
                        description : { type: string, boost: 5 }
                        tags: { type: string, boost: 5 }
                        keywords:
                           type: "nested"
                           properties:
                               tags : { type: string, boost: 5 }
                               category : { type: string, boost: 5 }

                    persistence:
                        driver: orm
                        model: Acme\ApplicationBundle\Entity\Post
                        model_to_elastica_transformer: ~
                        provider: ~
                        listener: ~
                        finder: ~

In above configuration we use automatic mapping between elasticasearch index and doctrine model. In other method we can use ‘model_to_elastica_transformer’ to setup complex elasticasearch.


fos_elastica:
    clients:				
        default: { host: localhost, port: 9200 }
    indexes:
        mysite:
            types:
                post:
                    persistence:
                        driver: orm
                        model: Acme\ApplicationBundle\Entity\Post
                        model_to_elastica_transformer:
                            service: mysite.transformers.model.post	# Create the mysite.transformers.model.post service
                        provider: ~
                        listener: ~
                        finder: ~

Populating the Elastic search index

When using the providers and listeners that come with the bundle, any new or modified object will be indexed automatically. In some cases, where the database is modified externally, the Elasticsearch index must be updated manually. This can be achieved by running the console command:

$ php app/console fos:elastica:populate

The command will also create all indexes and types defined if they do not already exist on the Elasticsearch server.

Method 3

Write Elastic search query using symfony FOSElastica Bundle and get the result from Elastica Model


After Integrating Elastic search into Symfony we will learn how to write search query in Symfony. The most useful searching method is to use a finder defined by the type configuration. A finder will return results that have been hydrated by the configured persistence backend, allowing you to use relationships of returned entities. For more information about configuration options for this kind of searching, please see the types documentation. To create elastic-search query we will follow some simple steps:We will create the query for below model:

{
"_index": "mysite",
"_type": "post",
"_id": "12498",
"_score": 1,
"_source": {
  "id": 12498,
  "title": "Characterization of the human ESC transcriptome by hybrid sequencing.",
  "description": "Proc Natl Acad Sci U S A",
  "tags": [
	'html',
	'css',
	'javascript',
	'php',
	'mysql'
  ],          
}

First set up a controller where we write a search action. To create Elastic search query you need to inject two services index(fos_elastica.index.mysite.post) and finder(fos_elastica.index.mysite.post).

Use following files into your controller

use FOS\ElasticaBundle\Elastica\Index;
use FOS\ElasticaBundle\Elastica\Finder;
public function searchAction(Request $request){
	$searchString = $request->get('search_string');
        $index = $this->get('fos_elastica.index.mysite.post');
        $finder = $this->get('fos_elastica.finder.mysite.post');

        $query = new \Elastica\Query();
        $filter = new \Elastica\Filter\BoolAnd();
        $boolFilter = new \Elastica\Filter\Bool();

	// Term search 
	// Search Result by title
        $titleTerm  = new \Elastica\Filter\Term();
        $titleTerm->setTerm("title", $searchString);
        $boolFilter->addMust($titleTerm);

	$filter->addFilter($boolFilter);
    	$filteredQuery = new \Elastica\Query\Filtered(null, $filter);
    	$query->setQuery($filteredQuery);

	$posts = $finder->find($query);

	// posts return all filterd results
	var_dump($posts);
}

We can use different types of a search query in FOSElastica search

Term Search

It is simple string/text search that exactly matches the string and returns a related result.

$titleTerm  = new \Elastica\Filter\Term();
$titleTerm->setTerm("title", $title);
$boolFilter->addMust($titleTerm);

Terms Search

This terms search is taking array parameter and search all array item in a text. We can also set all item should match or not using the setParam method.

$tagsTerm =  new \Elastica\Filter\Terms();
$tagsTerm->setTerms("tags", $searchTerms);
$tagsTerm->setParam("execution", "or");	// set 'or' or 'and' option

 

Write a Reply or Comment

Your email address will not be published. Required fields are marked *