简体   繁体   English

Lucene.net - 如何创建否定查询,即。搜索不包含某些内容的对象

[英]Lucene.net - How do I create a negative query, ie. search for objects NOT containing something

I'm working on an EPiServer website using a Lucene.net based search engine. 我正在使用基于Lucene.net的搜索引擎在EPiServer网站上工作。

I have a query for finding only pages with a certain pageTypeId. 我有查询只查找具有某个pageTypeId的页面。 Now I want to do the opposite, I want to only find pages that is NOT a certain pageTypeId. 现在我想做相反的事情,我想只找到不是某个pageTypeId的页面。 Is that possible? 那可能吗?

This is the code for creating a query to search only for pages with pageTypeId 1, 2 or 3: 这是用于创建查询以仅搜索pageTypeId为1,2或3的页面的代码:

public BooleanClause GetClause()
{
    var booleanQuery = new BooleanQuery();
    var typeIds = new List<string>();
    typeIds.Add("1");
    typeIds.Add("2");
    typeIds.Add("3");

    foreach (var id in this.typeIds)
    {
        var termQuery = new TermQuery(
            new Term(IndexFieldNames.PageTypeId, id));
        var clause = new BooleanClause(termQuery, 
            BooleanClause.Occur.SHOULD);
        booleanQuery.Add(clause);
    }
    return new BooleanClause(booleanQuery, 
        BooleanClause.Occur.MUST);
}

I want instead to create a query where I search for pages that have a pageTypeId that is NOT "4". 我想要创建一个查询,我在其中搜索pageTypeId不是“4”的页面。

I tried simply replacing "SHOULD" and "MUST" with "MUST_NOT", but that didn't work. 我尝试用“MUST_NOT”代替“SHOULD”和“MUST”,但这不起作用。


Thanks to @goalie7960 for replying so quickly. 感谢@ goalie7960快速回复。 Here is my revised code for searching for anything except some selected page types. 这是我修改的代码,用于搜索除某些选定页面类型之外的任何内容。 This search includes all documents except those with pageTypeId "1", "2" or "3": 此搜索包括除pageTypeId“1”,“2”或“3”之外的所有文档:

public BooleanClause GetClause()  
{
    var booleanQuery = new BooleanQuery();  
    booleanQuery.Add(new MatchAllDocsQuery(), 
        BooleanClause.Occur.MUST);

    var typeIds = new List<string>();  
    typeIds.Add("1");  
    typeIds.Add("2");  
    typeIds.Add("3");  

    foreach (var typeId in this.typeIds)  
    {
        booleanQuery.Add(new TermQuery(
            new Term(IndexFieldNames.PageTypeId, typeId)), 
            BooleanClause.Occur.MUST_NOT);
    }  
    return new BooleanClause(booleanQuery, 
        BooleanClause.Occur.MUST);  
}

Assuming all your docs have a pageTypeId you can try using a MatchAllDocsQuery and then a MUST_NOT to remove all the docs you want to skip. 假设您的所有文档都有pageTypeId,您可以尝试使用MatchAllDocsQuery,然后使用MUST_NOT删除您要跳过的所有文档。 Something like this would work I think: 我想这样的事情会起作用:

BooleanQuery subQuery = new BooleanQuery();
subQuery.Add(new MatchAllDocsQuery(), BooleanClause.Occur.MUST);
subQuery.Add(new TermQuery(new Term(IndexFieldNames.PageTypeId, "4")), BooleanClause.Occur.MUST_NOT);
return subQuery;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM