[英]searching for a keyword using whitespace analyzer
下面显示的是我的数据索引方法:
public void getAvailableItems(String sql) {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
IndexWriter writer=null;
File file = null;
try{
file = new File(LUCENE_INDEX_DIRECTORY);
analyzer = new WhitespaceAnalyzer(Version.LUCENE_CURRENT);
writer = new IndexWriter(
FSDirectory.open(file),
analyzer,
true,
IndexWriter.MaxFieldLength.LIMITED
);
Class.forName("com.mysql.jdbc.Driver").newInstance();
//get connection object
con = DriverManager.getConnection(
"jdbc:mysql://"+DB_HOST_NAME+"/evergoldbuilders", DB_USER_NAME, DB_PASSWORD);
//create statement object
stmt = con.createStatement();
//execute query
rs = stmt.executeQuery(sql);
//iterate through result set
while(rs.next()){
String name = rs.getString("category_name").trim() + " " + rs.getString("sub_category_name").trim() + " " + rs.getString("classification_name").trim() + " " + rs.getString("item_name").trim();
Document document = new Document();
Field nameField = new Field("item_complete_name", name, Field.Store.YES, Field.Index.ANALYZED);
document.add(nameField);
writer.addDocument(document);
}
writer.optimize();
}catch(Exception e){
e.printStackTrace();
}
}
和我搜索关键字的方法:
public void searchItem(String column, String search) throws Exception{
ScoreDoc[] hits = null;
QueryParser parser = null;
Query q = null;
int hitsPerPage = 50;
analyzer = new WhitespaceAnalyzer(Version.LUCENE_CURRENT);
File files = new File(LUCENE_INDEX_DIRECTORY);
IndexReader reader = IndexReader.open(FSDirectory.open(files),true);
IndexSearcher searcher = new IndexSearcher(reader);
TopScoreDocCollector collector = TopScoreDocCollector.create(hitsPerPage, true);
parser = new QueryParser(Version.LUCENE_CURRENT, "item_complete_name", analyzer);
q = parser.parse(search + "*");
searcher.search(q, collector);
hits = collector.topDocs().scoreDocs;
System.out.println("Found " + hits.length + " hits.");
count = 0;
for(int i=0;i<hits.length;++i) {
isFound = true;
int docId = hits[i].doc;
Document d = searcher.doc(docId);
System.out.println(d.getField("item_complete_name").stringValue());
count++;
}
searcher.close();
}
最后,我的样本数据建立了索引:
ALUMINUM 4'/O U.S. ALUMINUM
ALUMINUM 4" CHINA ALUMINUM
ALUMINUM 3'/O U.S. ALUMINUM
ALUMINUM 3"A CHINA ALUMINUM
PAINTS DAVIES 4 LITERS DV 472 HI-HEAT RESISTING ALUMINUM (1200°F)
PAINTS DAVIES 4 LITERS DV 470 SILVER FINISH ALUMINUM
我的问题是,每当我搜索“ alum *”时,都找不到搜索结果,但“ aluminum”却找到了。 在“铝和中国*”上找不到搜索结果。 我可以使用Lucene通配符(即*和?)来使用空白分析器搜索索引数据吗? 空格分析器会标记非字母吗? 我希望分析器将空间上的数据标记化。 空白分析仪是正确的选择吗? 非常感谢!
使用org.apache.lucene.analysis.standard。 StandardAnalyzer代替WhitespaceAnalyzer
可以解决此问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.