ElasticSearch NEST库检索某些字段

时间:2015-07-28 15:07:08

标签: elasticsearch selecteditem nest

尝试实现以下目标,

  • 检索与给定ID和流派相匹配的文章
  • 检索选定字段以匹配记录

我用Sense(chrome插件)

尝试了这个
POST /d3acampaign/article/_search
        {
            "fields": ["title","genre"] ,
            "query": {
                "filtered": {
                    "filter": {
                        "bool": {
                            "must": [{
                                    "term": {
                                    "id": "6"
                                }
                            },
                            {
                                    "term": {
                                    "genre": "metal"
                                }
                            }]
                        }
                    }
               }
            }
        }

对于C#代码,我尝试使用以下构造构建查询,

        FilterContainer fc = null;
        TermFilter title = new TermFilter()
        {
            Field = "id",
            Value = "6",
        };

        TermFilter genre = new TermFilter()
        {
            Field = "genre",
            Value = "metal",
        };

        fc = title & genre;
        QueryContainer qc = new FilteredQuery() { Filter = fc };
        var searchRequest = new SearchRequest
        {
            SearchType = Elasticsearch.Net.SearchType.QueryAndFetch,
            Query = qc,
            Indices = new IndexNameMarker[] {"journal"},
            Types = new TypeNameMarker[] { "article" },                
        };


        var r = client.SearchAsync<Article>(searchRequest);


        var l = (List<Article>) r.Result.Documents;

我能够运行此查询并获取匹配的记录,但我不确定如何指定要检索的选定字段。让我知道在C#代码中可以更改哪些内容以指定必要的字段。

提前致谢。

1 个答案:

答案 0 :(得分:1)

根据this回答,您可以修改您的请求对象,如下所示:

var searchRequest = new SearchRequest
{
    ...
    Fields = new List<PropertyPathMarker>
    {
        Property.Path<Article>(p => p.YourField)
    }
};

或者如果您决定使用source filtering

var searchRequest = new SearchRequest
{
    ...
    Source = new SourceFilter
    {
        Include = new []
        {
            Property.Path<Article>(p => p.YourField)
        }
    } 
};

希望它有所帮助。