Last active
August 29, 2015 14:06
-
-
Save robinfang/a68be43bf331be974391 to your computer and use it in GitHub Desktop.
lucene 4.10 basic searcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package hpcde; | |
| import java.io.File; | |
| import java.io.IOException; | |
| import org.apache.lucene.analysis.Analyzer; | |
| import org.apache.lucene.analysis.standard.StandardAnalyzer; | |
| import org.apache.lucene.document.Document; | |
| import org.apache.lucene.index.DirectoryReader; | |
| import org.apache.lucene.index.IndexReader; | |
| import org.apache.lucene.queryparser.classic.ParseException; | |
| import org.apache.lucene.queryparser.classic.QueryParser; | |
| import org.apache.lucene.search.IndexSearcher; | |
| import org.apache.lucene.search.Query; | |
| import org.apache.lucene.search.ScoreDoc; | |
| import org.apache.lucene.search.TopScoreDocCollector; | |
| import org.apache.lucene.store.FSDirectory; | |
| public class PostSearcher { | |
| public static void main(String[] args) throws IOException, ParseException { | |
| String queryStr = "八"; | |
| String indexPath = "G:\\luceneIndex"; | |
| IndexReader reader = DirectoryReader.open(FSDirectory.open(new File( | |
| indexPath))); | |
| IndexSearcher searcher = new IndexSearcher(reader); | |
| for (int i = 0; i < reader.maxDoc(); i++) { | |
| Document doc = reader.document(i); | |
| String mid = doc.get("content"); | |
| System.out.println(mid); | |
| } | |
| Analyzer analyzer = new StandardAnalyzer(); | |
| QueryParser parser = new QueryParser("content", analyzer); | |
| Query q = parser.parse(queryStr); | |
| TopScoreDocCollector collector = TopScoreDocCollector.create(10, true); | |
| searcher.search(q, collector); | |
| ScoreDoc[] hits = collector.topDocs().scoreDocs; | |
| System.out.println("Found " + hits.length + " hits."); | |
| for (int i = 0; i < hits.length; ++i) { | |
| int docId = hits[i].doc; | |
| Document d = searcher.doc(docId); | |
| System.out.println((i + 1) + ". " + d.get("content") + "\t" | |
| + d.get("mid") + "\t" + d.get("time") + "\t" | |
| + d.get("user_sname")); | |
| } | |
| reader.close(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment