有3种方法可以做到这一点。
第一种方法是手动构造查询,这是QueryParser内部的工作。这是执行此操作最强大的方法,这意味着如果要阻止访问以下某些更奇特的功能,则不必解析用户输入QueryParser:
IndexReader reader = IndexReader.Open("<lucene dir>");Searcher searcher = new IndexSearcher(reader);BooleanQuery booleanQuery = new BooleanQuery();Query query1 = new TermQuery(new Term("filename", "<text>"));Query query2 = new TermQuery(new Term("filetext", "<text>"));booleanQuery.add(query1, BooleanClause.Occur.SHOULD);booleanQuery.add(query2, BooleanClause.Occur.SHOULD);// Use BooleanClause.Occur.MUST instead of BooleanClause.Occur.SHOULD// for AND queriesHits hits = searcher.Search(booleanQuery);第二种方法是使用MultiFieldQueryParser,其行为类似于QueryParser,允许访问其具有的所有功能,只是它将搜索多个字段。
IndexReader reader = IndexReader.Open("<lucene dir>");Searcher searcher = new IndexSearcher(reader);Analyzer analyzer = new StandardAnalyzer();MultiFieldQueryParser queryParser = new MultiFieldQueryParser( new string[] {"filename", "filetext"}, analyzer);Hits hits = searcher.Search(queryParser.parse("<text>"));最后一种方法是使用QueryParser see here的特殊语法。
IndexReader reader = IndexReader.Open("<lucene dir>");Searcher searcher = new IndexSearcher(reader); Analyzer analyzer = new StandardAnalyzer();QueryParser queryParser = new QueryParser("<default field>", analyzer);// <default field> is the field that QueryParser will search if you don't // prefix it with a field.string special = "filename:" + text + " OR filetext:" + text;Hits hits = searcher.Search(queryParser.parse(special));您的另一种选择是创建新的领域时filenameandtext叫你索引你的内容,可以在其中放置的内容既文件名和FILETEXT,那么你只需要搜索一个领域。



