此查询失败(RavenDB 1.0.701)
var items= RavenSession.Query<Item>().Where(x => "161 193".StartsWith(x.MaterializedPath)).ToList();
还有别的办法吗?
在您问之前,我正在尝试使用materialized path (lineage column)获取树结构数据的父级(祖先)。
发布于 2012-03-30 11:01:12
在RavenDB中不能这样做-您要查询的字段必须位于谓词的左侧,而谓词的右侧不能引用另一个字段。
至于如何重组--对不起,我不确定。
编辑:
好吧,这需要一些实验--但我设法让它工作,如果有可能重构MaterializedPath,或添加一个新的属性。为了避免混淆,这里我假设它是一个新属性。
// Sample class:
public class Item
{
public string Name { get;set;}
public Dictionary<int, string> Path { get;set;} // Zero-based key on path.
}
// Query: Find nodes with path "A B"
var query = session.Query<Item>().AsQueryable();
query = query.Where(item => item.Path[0] == "A");
query = query.Where(item => item.Path[1] == "B");
var found = query.ToList();
现在它正在运行:
IDocumentStore store = new EmbeddableDocumentStore { RunInMemory = true };
store.Initialize();
// Install Data
using (var session = store.OpenSession())
{
session.Store(new Item("Foo1", "A")); // NB: I have a constructor on Item which takes the path and splits it up. See below.
session.Store(new Item("Foo2", "A B"));
session.Store(new Item("Foo3", "A C D"));
session.Store(new Item("Foo4", "A B C D"));
session.Store(new Item("Foo5", "C B A"));
session.SaveChanges();
}
using (var session = store.OpenSession())
{
var query = session
.Query<Item>().AsQueryable();
query = query.Where(item => item.Path[0] == "A");
query = query.Where(item => item.Path[1] == "B");
var found = query.ToList();
Console.WriteLine("Found Items: {0}", found.Count );
foreach(var item in found)
{
Console.WriteLine("Item Name {0}, Path = {1}", item.Name, string.Join(" ", item.Path));
}
}
其输出结果为:
Found Items: 2
Item Name Foo2, Path = [0, A] [1, B]
Item Name Foo4, Path = [0, A] [1, B] [2, C] [3, D]
希望这能有所帮助。
编辑2:
我在Item上的构造函数看起来像这样,只是为了便于测试:
public Item(string name, string materializedPath)
{
Name = name;
var tmpPath = materializedPath.Split(' ');
Path =
tmpPath
.Zip(Enumerable.Range(0, tmpPath.Count()), (item, index) => new {Item = item, Index = index})
.ToDictionary(k => k.Index, v => v.Item);
}
发布于 2012-03-30 22:43:38
我建议建立一个索引,它将包含搜索的每一种可能性。这将在您的索引中创建大量项目,但同时它也是Lucene快速搜索的强大功能
Map = docs => from n in docs
let allPaths = n.MaterializedPath.Split(new char[]{' '})
from path in allPaths
select new
{
Path = path
};
重要的是,"path“代表唯一的文档ID
https://stackoverflow.com/questions/9936369
复制相似问题