我想按年份,格式和内容过滤一组文档.
n伪SQL:
SELECT * FROM /test/document
WHERE
((format=f1|| format=f2||...|| format=fn) AND
(Year!=2013 AND Year!=2015) AND
(content like %c1% || content like %c2% ||...|| content like %cn%))
如您所见,格式和内容项的数量是动态的,将由用户选择.
到目前为止,我想出了如何分别对每个字段进行动态查询,然后使用bool查询将它们组合起来,如下面的代码所示;
// For YEAR
QueryContainer qYear=null;
foreach (var year in years)
{
qYear |= new TermQuery() { Field = "year", Value = year };
}
// For FORMAT
var qformat = new List<QueryContainer>();
foreach (var format in txtDocs)
{
qformat.Add(Query<Document>.Match(m => m.OnField(p => p.Format).Query(format)));
}
// For CONTENT
var qc = new List<QueryContainer>();
qc.Add(Query<Document>.Match(m => m.OnField(p => p.File).Query(discpString).Boost(2)));
qc.Add(Query<Document>.Match(m => m.OnField(p => p.File).Query(roleString)));
qc.Add(Query<Document>.Match(m => m.OnField(p => p.File).Query(taskString)));
qc.Add(Query<Document>.Match(m => m.OnField(p => p.File).Query(sysString).Boost(2)));
//MY QUERY
var searchResults = client.Search<Document>(s => s.Fields(f => f.Title, f => f.Format, f => f.Year, f => f.DateCreated, f => f.Id, f => f.Path, f => f.Size, f => f.Firstwords).
Index(defaultIndex).From(0).Size(100).
Query(q => q.Bool(b => b.MustNot(qYear).Should(qformat.ToArray()).Should(qc.ToArray()))));
当我运行此代码时,年份和内容字段的结果是我所期望的,但也包括不在筛选列表中的其他格式!我希望它只是检索具有所选格式的文档.
有谁知道我的错误在哪里?
解决方法:
我能找到我的错误!
我使用Querycontainer格式与我用于Year的命令相同,然后在我的查询中使用了Must.以下是代码的更改部分:
// For FORMAT
QueryContainer qF=null;
foreach (var format in txtDocs)
{
qF |= new TermQuery() { Field = "format", Value = format };
}
//MY QUERY
var searchResults = client.Search<Document>(s => s.Fields(f => f.Title, f => f.Format, f => f.Year, f => f.DateCreated, f => f.Id, f => f.Path, f => f.Size, f => f.Firstwords).
Index(defaultIndex).From(0).Size(100).
Query(q => q.Bool(b => b.MustNot(qYear).Must(qF).Should(qc.ToArray()))));