Finding objects which contains at least all elements from subset using RavenDB and LINQ

你离开我真会死。 提交于 2019-12-05 16:09:26
Ayende Rahien

Jarek, what you want to do is:

var q = session.Query<Question>();
foreach(var tag in tags)
{
    var currentTag = tag;
    q = q.Where(x=>x.Tags.Any(xTag=>xTag == currentTag));
}

This will give you all the questions that have at least all those tags.

It looks like the LINQ Provider did not implement Except as part of the Query Pattern. If I understand your requirement enough, you might be able to use SequenceEquals.

var result = questions.Where(q => q.Tags.SequenceEqual(tags));

Using the code you provided, this returned exactly one result {"aa","bb"}. If the RavenDB Provider doesn't provide enough of the Query Pattern implementation for you, then just do it without using LINQ at all.

The RavenDB LINQ provider doesn't support this syntax because the underlying index mechanism (Lucene) doesn't allow this type of query.

However there is a new feature in RavenDB that will allow you to do this, see this thread for more info. Note you'll need to get the latest build to be able to use this feature.

You should be able to write your query as:

var result = session.Query<Question>("IndexName")
        .Where(x => x.Tags.Any(t => t == "aa"))
        .Intersect()
        .Where(x => x.Tags.Any(t => t == "bb")
        .ToList();

And the index needs to look something like this:

from qu in docs.Questions
from tag in qu.Tags
select new { tag }

Thanks, I've been looking for another scenario for this new feature, so when I get a chance I'll create a gist showing the full sample.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!