如何创建一个返回字符串列表的RavenDB索引?

Dav*_*all 5 c# linq json mapreduce ravendb

我在表格上有一系列文件"WineDocument":

{
  "Name": "Barbicato Morellino Di Scansano",
  "Country": "Italy",
  "Region": "Tuscany",
}
Run Code Online (Sandbox Code Playgroud)

我需要进行查询以查找"Country"字段的所有唯一值.我一直在尝试创建一个类似于的索引:

class WineCountriesIndex: AbstractIndexCreationTask<WineDocument, string> {
        public BeverageCountriesIndex() {
            Map = wines => from wine in wines
                           where wine.Country != null
                           select new { Key = wine.Country };
            Reduce = results => from result in results
                                group result by result into g
                                select new { Key = g.Key };
        }
    }
Run Code Online (Sandbox Code Playgroud)

索引创建正常,我尝试使用以下代码:

IList<string> countries = session.Query<string, WineCountriesIndex>().ToList();
Run Code Online (Sandbox Code Playgroud)

但是这会产生一个JsonSerializationException:"无法将JSON对象反序列化为类型'System.String'.".我想这是因为Json解析器无法将{Key ="Italy}解析为字符串.但我不知道如何使map/reduce返回一个字符串.

Dav*_*all 7

我不知道这是不是最好的方法,但这就是我解决它的方法.我创建了一个索引,看起来像:

class WineCountriesIndex: AbstractIndexCreationTask<WineDocument, WineCountriesIndex.Result> {
    public class Result {
        public string Country { get; set; }
    }

    public WineCountriesIndex() {
        Map = wines => from wine in wines
                       where wine.Country != null
                       select new { Country = wine.Country };
        Reduce = results => from result in results
                            group result by result.Country into g
                            select new { Country = g.Key };
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我使用此代码进行实际查询:

using(IDocumentSession session = _store.OpenSession()) {
    return session.Query<WineCountriesIndex.Result, WineCountriesIndex>().Select(country => country.Country).ToList();
}
Run Code Online (Sandbox Code Playgroud)