我在表格上有一系列文件“WineDocument”:
{
"Name": "Barbicato Morellino Di Scansano",
"Country": "Italy",
"Region": "Tuscany",
}
我需要进行查询以查找“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 };
}
}
索引创建正常,我尝试使用以下代码:
IList<string> countries = session.Query<string, WineCountriesIndex>().ToList();
但是这会产生一个JsonSerializationException:“无法将JSON对象反序列化为'System.String'类型。”我想这是因为Json解析器无法将{Key =“Italy}解析为字符串。但我不知道如何使map / reduce返回一个字符串。
答案 0 :(得分: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 };
}
}
然后我使用此代码进行实际查询:
using(IDocumentSession session = _store.OpenSession()) {
return session.Query<WineCountriesIndex.Result, WineCountriesIndex>().Select(country => country.Country).ToList();
}
答案 1 :(得分:1)
问题是你的索引没有输出字符串,而是输出一个Key属性为字符串的对象。如果你真的想要,你会做一个投影,但我认为大卫的答案更好。