Is it possible to boost 'newest' items using elasticsearch? (FOQElasticaBundle)

后端 未结 3 1820
广开言路
广开言路 2020-12-07 15:22

I\'m currently implementing elasticsearch in my Symfony2 application via the FOQElasticaBundle and so far it\'s been working great based on boosts applied to various fields

3条回答
  •  青春惊慌失措
    2020-12-07 15:35

    Whew, after much experimentation and hours of trawling the Interweb I finally managed to get the desired behavior! (Full credit goes to Clinton Gormley.)

    Mapping configuration:

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

    Here is the code using the PHP client, Elastica, to dynamically build the query to boost using the original mapping AND the published date:

    $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);
    

    And for those of you more interested in the raw elasticsearch query (only with 3 date ranges for brevity)...

    curl -XPOST 'http://localhost:9200/website/story/_search?pretty=true' -d '
    {
      "query" : {
        "bool" : {
          "must" : {
            query_string: {
              query: ""
            }
          },
          "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>"
                }
              }
            }
          ]
        }
      }
    }'
    

提交回复
热议问题