【问题标题】:RavenDB static index on dictionaryRavenDB 字典上的静态索引
【发布时间】:2012-07-13 15:53:28
【问题描述】:

我有一个使用文档的应用程序,其中包含字典中的属性列表,出于某种原因,我们需要使用静态索引并查询/过滤这些属性。

原型如下所示:

class Program
{
    static void Main(string[] args)
    {
        IDocumentStore store = new DocumentStore() { DefaultDatabase = "Test", Url = "http://localhost:8081" };
        store.Initialize();

        IndexCreation.CreateIndexes(typeof(Program).Assembly, store);

        using (var session = store.OpenSession())
        {
            session.Store(new Document { Id = "1", Name = "doc_name", Attributes = new Dictionary<string, object> { { "Type", "1" }, { "Status", "Active" } } });
            session.SaveChanges();
        }

        using (var session = store.OpenSession())
        {
            // works
            var l1 = session.Query<Document, Documents_Index>().Where(a => a.Attributes["Type"] == "1").ToList();
            // not working
            var l2 = session.Query<Document, Documents_Index>().Where(a => a.Attributes["Status"] == "Active").ToList();
        }
    }
}

public class Documents_Index : AbstractIndexCreationTask<Document>
{
    public Documents_Index()
    {
        Map = docs => docs.Select(a =>
         new
         {
             a.Name,
             a.Attributes,
             Attributes_Type = a.Attributes["Type"]
         });
    }
}

[Serializable]
public class Document
{
    public string Id { get; set; }
    public string Name { get; set; }
    public Dictionary<string, object> Attributes { get; set; }
}

但由于我需要使用任意属性名称/值进行查询,因此该索引确实解决了我们的问题。实际上属性列表在运行时是已知的(因此我们尝试修改 Map 表达式以注入任意数量的属性名称,但到目前为止我们还没有成功)。有没有办法以某种动态方式定义索引?

【问题讨论】:

    标签: ravendb


    【解决方案1】:

    你需要这样写:

    public class Documents_Index : AbstractIndexCreationTask<Document>
    {
        public Documents_Index()
        {
            Map = docs => docs.Select(a =>
             new
             {
                 a.Name,
                 _ = a.Attributes.Select(x=>CreateField("Attributes_"+x.Key, x.Value),
             });
        }
    }
    

    【讨论】:

    • 按预期工作,但意识到“_”属性名称很重要,不能更改
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多