2015-01-21 73 views
4

我使用fos_elastica在symfony2項目中實現elasticsearch。彈性搜索:如何獲得大多數研究的術語

萬物工作正常(索引數據,更新等)

I M目前正在尋找用戶行爲分析:我想獲得的10個用戶搜索或關鍵字,以重新查詢它。

例如:

如果搜索的45%是關於黃色氣球和45%是關於紅色的氣球,我想提出我的首頁上一些黃色或紅色氣球

首先,我想關於創建一個symfony2實體來保存帶有時間戳的用戶搜索,然後計算最後1000次搜索以獲得最有名的關鍵字。雖然它肯定會起作用,但那會是資源殺手。

我想知道elasticsearch是否能夠提供這些以及如何實現它。

我讀過,我可以創建一個索引來存儲我的用戶查詢(這將是awsome,因爲我可以使用方面來計算它們真的很容易),但我不知道如何做直接保存在彈性沒有專門的實體從symfony2搜索。

回答

3

好吧,我終於明白了!

這裏有不同的步驟:

1)創建config.yml一個新的索引與特定映射爲您的關鍵字搜索

in config.yml 

indexes: 
    your_index: 
     types: 
      search: 
       mappings: 
        value: {type:string} 
        date : {type:date} 
        provider: acme\AppBundle\Service\SearchProvider 

2)創建服務目錄

一個新的類SearchProvider
in acme\Appbundle\Service\SearchProvider 

<?php 


namespace acme\AppBundle\Service; 

use FOS\ElasticaBundle\Provider\ProviderInterface; 
use Elastica\Type; 
use Elastica\Document; 

class SearchProvider implements ProviderInterface 
{ 
protected $searchType; 
private  $search; 

public function __construct(Type $searchType) 
{ 
    $this->searchType = $searchType; 
} 

// the function you will call from your service 
public function add($search) 
{ 
    $this->search = $search; 
    $this->populate(); 
} 

/** 
* Insert the repository objects in the type index 
* 
* @param \Closure $loggerClosure 
* @param array $options 
*/ 
public function populate(\Closure $loggerClosure = null, array $options = array()) 
{ 
    if ($loggerClosure) { 
     $loggerClosure('Indexing users'); 
    } 

    $date = time(); 

    $document = new Document(); 
    $document->setData(array('value' => $this->search, 'date' => $date)); 
    $this->userType->addDocuments(array($document)); 
    $this->userType->getIndex()->refresh(); 
} 
} 

3)在service.yml創建新的服務聲明

services: 
acme.search_provider: 
    class: acme\AppBundle\Service\SearchProvider 
    arguments: 
     - @fos_elastica.index.recetas.search 
    tags: 
     - { name: fos_elastica.provider, index: your_index, type: search } 

4)打電話給你的服務來存儲新的搜索這樣

$this->get("acme.search_provider")->add("kapoue"); 

kapoue將被添加到搜索。

5)得到所有的搜索關鍵詞,並聚集它排在

$es     = $this->get('fos_elastica.index.acme.search'); 
    $query    = new \Elastica\Query(); 

    $aggregation  = new \Elastica\Aggregation\Terms("top_hits"); 
    $aggregation->setField('value'); 
    $aggregation->setSize(3); 

    $query->addAggregation($aggregation); 

    $result    = $es->search($query); 
    $mostResearched  = $result->getAggregation("top_hits"); 

    print_r ($mostResearched); die();