我读到How to incorporate multiple fields in QueryParser?但我没明白。
目前我有一个非常奇怪的结构,例如:
parser = New QueryParser("bodytext", analyzer)
parser2 = New QueryParser("title", analyzer)
query = parser.Parse(strSuchbegriff)
query2 = parser.Parse(strSuchbegriff)
我可以做什么:
parser = New QuerParser ("bodytext" , "title",analyzer)
query =parser.Parse(strSuchbegriff)
因此解析器在“bodytext”字段和“title”字段中查找搜索词。
最佳答案
有 3 种方法可以做到这一点。
第一种方法是手动构造查询,这是 QueryParser 内部所做的事情。这是最强大的方法,并且意味着如果您想阻止访问 QueryParser
的一些更奇特的功能,则不必解析用户输入:
IndexReader reader = IndexReader.Open("<lucene dir>");
Searcher searcher = new IndexSearcher(reader);
BooleanQuery booleanQuery = new BooleanQuery();
Query query1 = new TermQuery(new Term("bodytext", "<text>"));
Query query2 = new TermQuery(new Term("title", "<text>"));
booleanQuery.add(query1, BooleanClause.Occur.SHOULD);
booleanQuery.add(query2, BooleanClause.Occur.SHOULD);
// Use BooleanClause.Occur.MUST instead of BooleanClause.Occur.SHOULD
// for AND queries
Hits 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[] {"bodytext", "title"},
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 = "bodytext:" + text + " OR title:" + text;
Hits hits = searcher.Search(queryParser.parse(special));
您的另一种选择是在索引内容时创建名为 bodytextandtitle 的新字段,您可以将正文和标题的内容放入其中,然后您只需搜索一个字段。 p>
关于java - 如何在 Lucene QueryParser 中指定两个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2005084/