Search for objects containing at least one element from a subset using RavenDB and LINQ

I have a simple type Question:

public class Question
{
    public Question(string id)
    {
        Id = id;
        Tags = new List<string>();
    }

    public string Id { get; private set; }
    public IList<string> Tags { get; set; }            
}

I defined a sample of the following questions:

var q1 = new Question("q1") { Tags = new List<string>() {"a"} };
var q2 = new Question("q2") { Tags = new List<string>() {"b"} };
var q3 = new Question("q3") { Tags = new List<string>() {"a", "b", "c"} };
var q4 = new Question("q4") { Tags = new List<string>() {"a", "b"} };
var q5 = new Question("q5") { Tags = new List<string>() {"z"} };
var q6 = new Question("q6");
var questions = new List<Question>() {q1, q2, q3, q4, q5, q6};

Now I need to find all the questions containing at least one tag from this subset . The subset is defined below:

string[] tags = new[] {"a", "b"};

I expect q1 , q2 , q3 and q4 to return . The query that I use to get the desired result is as follows:

var questions = DocumentSession.Query<Question>().AsQueryable();
questions = GetQuestionsToContainingAtLeastOneTagFromSubset(questions, tags)
// some other query restrictions
var result = questions.ToList(); // (**)

The function, which involves imposing restrictions on my collection, is as follows:

private IQueryable<Question> GetQuestionsToContainingAtLeastOneTagFromSubset(IQueryable<Question> questions, IEnumerable<string> tags)
{
    var result = new List<Question>();
    foreach (var tag in tags)
    {
        var currentTag = tag;
        var resultForTag = questions.Where(x => x.Tags.Any(xTag => xTag == currentTag));
        result = result.Concat(resultForTag).ToList();
     }
     return result.GroupBy(x => x.Id).Select(grp => grp.First()).AsQueryable();
}

, . .ToList() . , .ToList() RavenDB (BTW: ?). . . (**) RavenDB .

?

+3
2

lucene, , yor tag aray :

string[] tags = new[] { "a", "b" };
string queryRange = "(" + string.Join(" OR ", tags) + ")";

var res = session.Advanced.LuceneQuery<Question>()
               .Where("Tags:" + queryRange).ToList();

, , . , - GUESS - . . Lucene: http://lucene.apache.org/core/old_versioned_docs/versions/3_0_0/queryparsersyntax.html

0

:

 var q1 = new Question("q1") { Tags = new List<string>() {"aa", "bb"} };
 var q2 = new Question("q2") { Tags = new List<string>() {"aa"} };
 var q3 = new Question("q3") { Tags = new List<string>() {"aa", "bb", "cc"} };
 var q4 = new Question("q4");
 var questions = new List<Question>() {q1, q2, q3, q4};
 string[] tags = new[] { "bb", "cc" };

 var res = (from p in questions where 
           (from q in tags where p.Tags.Contains(q) == true select p).ToArray().Count() >= 1 
            select p).Distinct(); 
 //If you want more speed you can try to add .AsParallel() after .Distinct()
0

All Articles