【问题标题】:How to create a RavenDB index that returns a list of strings?如何创建返回字符串列表的 RavenDB 索引?
【发布时间】:2012-01-17 03:59:25
【问题描述】:

我在表单上有一组文档“WineDocument”:

{
  "Name": "Barbicato Morellino Di Scansano",
  "Country": "Italy",
  "Region": "Tuscany",
}

我需要进行查询以查找“国家/地区”字段的所有唯一值。我一直在尝试创建一个看起来像这样的索引:

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 只返回一个字符串。

【问题讨论】:

  • wine.Country 是一个枚举?
  • 不,它是一个字符串。它的可能值在编译时是未知的。

标签: c# json linq mapreduce ravendb


【解决方案1】:

我不知道这是否是最好的解决方法,但这就是我解决它的方法。我创建了一个如下所示的索引:

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();
}

【讨论】:

    【解决方案2】:

    问题是您的索引不是输出字符串,而是输出具有 Key 属性的对象,该属性是字符串。如果你真的想要,你会做一个预测,但我认为大卫的答案更好。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 1970-01-01
      • 2021-03-14
      • 2017-03-13
      • 2023-03-07
      • 2016-09-20
      相关资源
      最近更新 更多