c#elastic search nest如何输出文档分数

时间:2015-09-15 07:44:08

标签: c# elasticsearch nest

我想输出弹性搜索的每个结果的分数。但我不确定如何才能得到这个。

以下是我当前运行查询的代码:

  var searchResults = client.Search<Place>(s => s
             .From(0)
             .Size(5)
             .Explain(true)
             .TrackScores(true)
             .Query(q => q

                    .QueryString(fqqs1 => fqqs1
                        .OnFieldsWithBoost(d => d
                            .Add("name", 5.0)
                        )
                        .Query("west midlands birmingham")
                    )

             )
             .Sort(sort => sort.OnField("_score").Descending())
             .Sort(sort => sort.OnField(f => f.id).Ascending())
       );

// Output the results to console
        Console.WriteLine("\nTotal Hits: " + searchResults.HitsMetaData.Hits.Count + " out of " + searchResults.HitsMetaData.Total);

        List<Result> results = new List<Result>();
        foreach (Place result in searchResults.Documents)
        {
            results.Add(new Result
            {
                woeid = Convert.ToInt32(result.id),
                name = result.name,
                admin1 = result.admin1,
                admin2 = result.admin2,
                type = result.type
            });
            Console.WriteLine(result.id + " > " + result.name + " > " + result.admin1 + " > " + result.admin2 + " > " + result.type); 
        }

2 个答案:

答案 0 :(得分:3)

使用.Hits上的ISearchResponse<T>属性集合 - 该集合包含.Score属性中每个文档的分数,以及.Source属性中的文档

答案 1 :(得分:0)

您可以按分数排序。例如:排序(sort => sort.OnField(“ _ score”)。Descending())

 var result = client.Search(q => q
                 .Index(your-index-name)
                 .From(0)
                 .Type("post")
                 .Fields("firstName","LastName")
                 .TrackScores(true)
                 .Size(12) 
                 .Query(SearchQuery)                           
                 .Sort(sort => sort.OnField("_score").Descending())
                );

Nest 7的代码示例

var sorts = new List<ISort>();
sorts.Add(new FieldSort { Field = "_score", Order = SortOrder.Descending });

var searchRequest = new SearchRequest<ElasticIndexGroupProduct>()
            {
                Profile = true,
                From = (pageNumber - 1) * pageSize,
                Size = pageSize,
                Version = true,
                Sort = sorts,
                Query = new MatchAllQuery()
                Aggregations = aggrigations
            };

 var searchResponse = _client.Search<ElasticIndexGroupProduct>(searchRequest);