2013-01-16 80 views
8

我在C#中使用NEST强类型客户端使用Elastic Search。 我有一个包含条目索引:使用NEST Field Boosting的弹性搜索

[ElasticType(Name = "Entry", IdProperty = "Id")] 
public class Entry 
{ 
    public string Id { get; set; } 
    public string Title { get; set; } 
    public string Description { get; set; } 
    public string Award { get; set; } 
    public int Year { get; set; } 
} 

其中year是入门,如2012年,奖奖项赢得的类型,它可以为null。

然后我想要使用不同属性的提升来搜索这些条目。在下面的代码中,我希望结果在标题上的排名要高于在说明上匹配的结果。

private IQueryResponse<Entry> GetMatchedEntries(string searchText) 
{ 
    return _elasticClient.Search<Entry>(
       body => 
       body.Query(q => 
          q.QueryString(qs => 
             qs.OnFieldsWithBoost(d => 
                   d.Add(entry => entry.Title, 5.0) 
                   .Add(entry => entry.Description, 2.0)) 
          .Query(searchText)))); 
} 

我现在被要求通过那些已经赢得奖励的人来提升结果,并且还提升了更新的参赛作品(即年度)。

我该怎么做?这是否需要作为索引服务的一部分来完成,还是作为搜索的一部分?

回答

12

您可以通过boosting查询和custom_score查询的组合

,而不是推动今年实现这一目标,我们改变基础上,今年的分数,因为:

(_score + 2013) > (_score + 1999) 

较新的结果会浮到顶部。

通过使用提升查询,我们可以有效降级缺少奖励字段的结果。

看到: http://www.elasticsearch.org/guide/reference/query-dsl/boosting-query.html http://www.elasticsearch.org/guide/reference/query-dsl/custom-score-query.html

_client.Search<Entry>(s=>s 
    .Query(q =>q 
     .Boosting(bq=>bq 
      .Positive(pq=>pq 
       .CustomScore(cbf=>cbf 
        .Query(cbfq=>cbfq 
         .QueryString(qs => qs 
          .OnFieldsWithBoost(d => 
           d.Add(entry => entry.Title, 5.0) 
           .Add(entry => entry.Description, 2.0) 
          ) 
          .Query(searchText) 
         ) 
        ) 
        .Script("_score + doc['year'].value") 
       ) 
      ) 
      .Negative(nq=>nq 
       .Filtered(nfq=>nfq 
        .Query(qq=>qq.MatchAll()) 
        .Filter(f=>f.Missing(p=>p.Award)) 
       ) 
      ) 
      .NegativeBoost(0.2) 
     ) 
    ) 
); 
+0

感谢张贴此马亭 - 肯定比当前文档更有帮助。 –

+1

应该指出的是,这将只适用于Elasticsearch <1.0。您应该在Elasticsearch> = 1.0中使用函数得分查询。 https://www.elastic.co/guide/en/elasticsearch/reference/0.90/query-dsl-function-score-query.html。另请参阅https://www.elastic.co/guide/en/elasticsearch/reference/0.90/query-dsl-function-score-query.html的解决方案 –