Elasticsearch推荐图书作者:如何限制每位作者最多3本书?

时间:2014-10-14 12:30:41

标签: elasticsearch recommendation-engine

我使用Elasticsearch推荐作者(我的Elasticsearch文档代表书籍,标题,摘要和作者ID列表)。

用户使用一些文本(例如GeorgiaParis)查询我的索引,我需要在作者级别汇总各个书籍的分数(意思是:推荐撰写有关巴黎的作者) 。

我从一个简单的聚合开始,但是,通过实验(交叉验证),最好在每个用户最多4本书之后停止聚合每个用户的分数。这样,我们就没有一本拥有200本可以“支配”结果的书籍的作者。让我用伪代码解释一下:

# the aggregated score of each author
Map<Author, Double>  author_scores = new Map()
# the number of books (hits) that contributed to each author
Map<Author, Integer> author_cnt = new Map()

# iterate ES query results
for Document doc in hits:

    # stop aggregating if more that 4 books from this author have already been found
    if (author_cnt.get(doc.author_id) < 4):
        author_scores.increment_by(doc.author_id, doc.score)
        author_cnt.increment_by(doc.author_id, 1)

the_result = author_scores.sort_map_by_value(reverse=true)

到目前为止,我已经在自定义应用程序代码中实现了上述聚合,但我想知道是否可以使用Elasticsearch的查询DSL或org.elasticsearch.search.aggregations.Aggregator接口重写它。

1 个答案:

答案 0 :(得分:2)

我的意见是你不能用ES提供的功能来做到这一点。我能找到的关于你的要求的最接近的是"top_hits" aggregation。有了这个,你执行你的查询,你聚合你想要的任何东西,然后你说你只需要按标准排序的前X点击。

对于您的特定情况,您的查询是&#34;匹配&#34;对于&#34; Paris&#34;,聚合在作者ID上,然后您告诉ES只返回前3本书,按每位作者的分数排序。好的部分是,ES将为每位特定的作者提供最好的三本书,按相关性排序,而不是每本书的所有书籍都没有。不太好的部分是&#34;顶级&#34;不允许另一个子聚合仅为那些&#34;热门歌曲&#34;提供分数总和。在这种情况下,您仍然需要计算每位作者的分数总和。

示例查询:

{
  "query": {
    "match": {
      "title": "Paris"
    }
  },
  "aggs": {
    "top-authors": {
      "terms": {
        "field": "author_ids"
      },
      "aggs": {
        "top_books_hits": {
          "top_hits": {
            "sort": [
              {
                "_score": {
                  "order": "desc"
                }
              }
            ],
            "_source": {
              "include": [
                "title"
              ]
            },
            "size": 3
          }
        }
      }
    }
  }
}