問題描述
我閱讀了 如何在 QueryParser 中合并多個字段? 但我沒聽懂.
I read How to incorporate multiple fields in QueryParser? but i didn't get it.
目前我有一個非常奇怪的結構,例如:
At the moment i have a very strange construction like:
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"字段中查找搜索詞.
so the Parser looks for the searching word in the field "bodytext" an in the field "title".
推薦答案
有 3 種方法可以做到這一點.
There are 3 ways to do this.
第一種方式是手動構造查詢,這就是QueryParser
在內部做的.這是最有效的方法,這意味著如果您想阻止訪問 QueryParser
的一些更奇特的功能,則不必解析用戶輸入:
The first way is to construct a query manually, this is what QueryParser
is doing internally. This is the most powerful way to do it, and means that you don't have to parse the user input if you want to prevent access to some of the more exotic features of 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
,允許訪問它擁有的所有功能,除了它會搜索多個字段.
The second way is to use MultiFieldQueryParser
, this behaves like QueryParser
, allowing access to all the power that it has, except that it will search over multiple fields.
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
的特殊語法看這里.
The final way is to use the special syntax of 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 的新字段,您可以將 bodytext 和標題的內容放入其中,然后您只需搜索一個字段.
Your other option is to create new field when you index your content called bodytextandtitle, into which you can place the contents of both bodytext and title, then you only have to search one field.
這篇關于如何在 Lucene QueryParser 中指定兩個字段?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!