弹性搜索:如何获得研究最多的术语

Cha*_*nel 5 symfony elasticsearch

我用fos_elastica在symfony2项目中实现了Elasticsearch。

一切正常(索引数据,更新等)

我目前正在寻找用户行为分析:我想获得10个最多的用户搜索或关键字,以便重新查询它。

例如 :

如果45%的搜索是关于黄色气球的,而45%的搜索是关于红色气球的,我想在我的主页上建议一些黄色或红色的气球

首先,我正在考虑创建symfony2实体,以使用时间戳保存用户搜索,然后计算最近1000次搜索以获取最著名的关键字。尽管它肯定会起作用,但这将是资源杀手。

我想知道Elasticsearch是否能够提供这些以及如何实现它。

我已经读过我可以创建一个索引来存储我的用户查询(那太麻烦了,因为我可以很方便地使用facet来计算它们),但是我不知道如何在没有symfony2的弹性搜索中直接保存它一个专门的实体。

Cha*_*nel 3

好吧,我终于明白了!

以下是不同的步骤:

1) 在 config.yml 中创建一个新索引,其中包含关键字搜索的特定映射

in config.yml

indexes:
    your_index:
        types:
            search:
                mappings:
                    value: {type:string}
                    date : {type:date}
                    provider: acme\AppBundle\Service\SearchProvider
Run Code Online (Sandbox Code Playgroud)

2)在Service目录下新建一个类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();
}
}
Run Code Online (Sandbox Code Playgroud)

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 }
Run Code Online (Sandbox Code Playgroud)

4)调用您的服务来存储新的搜索,如下所示

$this->get("acme.search_provider")->add("kapoue"); 
Run Code Online (Sandbox Code Playgroud)

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();
Run Code Online (Sandbox Code Playgroud)