字典上的RavenDB静态索引

时间:2012-07-12 11:56:22

标签: ravendb

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

原型看起来像这样:

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表达式以注入任意数量的属性名称,但到目前为止我们还没有成功)。有没有办法以某种动态方式定义索引?

1 个答案:

答案 0 :(得分:6)

你需要写它:

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