小编典典

使用Elasticsearch是否可以推广“最新”商品?(FOQElasticaBundle)

elasticsearch

我目前正在通过FOQElasticaBundle在我的Symfony2应用程序中实现elasticsearch,到目前为止,基于对“
Story”实体的各个领域应用的提升,它的运行一直很好。这是配置:

foq_elastica:
    clients:
        default: { host: localhost, port: 9200 }

    indexes:
        website:
            client: default
            types:
                story:
                    mappings:
                        title: { boost: 8 }
                        summary: { boost: 5 }
                        text: { boost: 3 }
                        author:
                    persistence:
                        driver: orm # orm, mongodb, propel are available
                        model: Acme\Bundle\StoryBundle\Entity\Story
                        provider:
                            query_builder_method: createIsActiveQueryBuilder
                        listener:
                            service: acme_story.search_index_listener
                        finder:

但是,我也想根据故事的“
published_at”日期进行调整,以使昨天发布的故事出现在6个月前发布的故事之前的结果中,即使较早的故事得分更高(显然,这需要一些调整)。这可能吗?

如果有人可以让我知道如何使用FOQElasticaBundle实现这一点,那还是不错的,但是如果您可以让我知道如何直接在Elasticsearch中实现这一点,那么我将不胜感激,以便我自己尝试实现这种行为,并为如果需要,请捆绑。

谢谢。


阅读 329

收藏
2020-06-22

共1个答案

小编典典

经过大量的实验和数小时的拖曳Interweb的努力,我终于设法达到了期望的行为!(值得称赞的克林顿·戈姆利。)

映射配置:

mappings:
    title: { boost: 8 }
    summary: { boost: 5 }
    text: { boost: 3 }
    author:
    publishedAt: { type: date }

以下是使用PHP客户端Elastica来动态构建查询以使用原始映射和发布日期进行增强的代码:

$query = new \Elastica_Query_Bool();
$query->addMust(new \Elastica_Query_QueryString($queryString));

$ranges = array();
for ($i = 1; $i <= 5; $i++) {
    $date = new \DateTime("-$i month");

    $currentRange = new \Elastica_Query_Range();
    $currentRange->addField('publishedAt', array(
        'boost' => (6 - $i),
        'gte' => $date->getTimestamp()
    ));

    $ranges[] = $currentRange->toArray();
}

$query->addShould($ranges);

/** @var $pagerfanta Pagerfanta */
$pagerfanta = $this->getFinder()->findPaginated($query);

对于那些对原始Elasticsearch查询更感兴趣的人(为简洁起见,仅使用3个日期范围)…

curl -XPOST 'http://localhost:9200/website/story/_search?pretty=true' -d '
{
  "query" : {
    "bool" : {
      "must" : {
        query_string: {
          query: "<search term(s)>"
        }
      },
      "should" : [
        {
          "range" : {
            "publishedAt" : {
              "boost" : 5,
              "gte" : "<1 month ago>"
            }
          }
        },
        {
          "range" : {
            "publishedAt" : {
              "boost" : 4,
              "gte" : "<2 months ago>"
            }
          }
        },
        {
          "range" : {
            "publishedAt" : {
              "boost" : 3,
              "gte" : "<3 months ago>"
            }
          }
        }
      ]
    }
  }
}'
2020-06-22