我是lucene的新手。我想存储和检索数据库中的数据。我还想存储表信息,以便我可以告诉数据属于哪个表并为用户加载表。
我能够将数据存储为来自数据库的文本,但我无法找出任何可以让我知道它来自哪个表的方法。
我已达到此级别,这使我可以将数据存储到索引文件中:
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
Events event=Event.getEventById(5);
Version matchVersion= Version.LUCENE_30;
Analyzer analyzer=new StandardAnalyzer(matchVersion);
boolean recreateIndexIfExists = true;
File indexDir=new File(INDEX_DIRECTORY);
Directory fsDir = FSDirectory.open(indexDir);
IndexWriter indexWriter= new IndexWriter(fsDir,analyzer,MaxFieldLength.UNLIMITED);
if(event !=null){
Document doc=new Document();
doc.add(new Field("field", event.getTitle(), Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("field", event.getPlace(), Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("field", event.getDescription(), Field.Store.YES, Field.Index.ANALYZED));
indexWriter.addDocument(doc);
}
indexWriter.optimize();
indexWriter.close();
searchIndex("first");
}
这是从索引文件中搜索:
File indexDir=new File(INDEX_DIRECTORY);
Directory fsDir = FSDirectory.open(indexDir);
if(indexDir.exists()){
System.out.println("index file found");
}else{
System.out.println("not found");
}
IndexReader indexReader=IndexReader.open(fsDir);
IndexSearcher searcher=new IndexSearcher(indexReader);
Version matchVersion= Version.LUCENE_30;
Analyzer analyzer=new StandardAnalyzer(matchVersion);
QueryParser parser=new QueryParser(matchVersion, "field", analyzer);
Query query;
try {
query = parser.parse(searchString);
int n=10;
TopDocs topDocs= searcher.search(query,n);
ScoreDoc[] scoreDocs=topDocs.scoreDocs;
System.out.println("hits= "+scoreDocs.length);
for (int i = 0; i < scoreDocs.length; ++i) {
ScoreDoc sd = scoreDocs[i];
System.out.println("scoredocs: "+scoreDocs[i]);
float score = sd.score;
int docId = sd.doc;
Document d = searcher.doc(docId);
Field value = (Field) d.getField("place");
System.out.println("placesdfgddd: "+value);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
答案 0 :(得分:1)
您的文档结构有点奇怪。我通常希望标题,位置和描述存储为单独的字段,而不是全部存储在名为“字段”的相同字段中。当然,这取决于您和您的搜索要求。
要存储表名,只需将其放入存储字段即可。由于您听起来不需要搜索,因此可以将其设置为Field.Index.NO
:
Document doc=new Document();
//Note, changed these field names.
doc.add(new Field("title", event.getTitle(), Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("place", event.getPlace(), Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("description", event.getDescription(), Field.Store.YES, Field.Index.ANALYZED));
doc.add(new Field("table", yourTableName, Field.Store.YES, Field.Index.NO));
其中,一旦获得搜索结果,就可以进行足够的检索:
document.getField("table").stringValue();