1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.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;
import org.apache.lucene.util.Version;

import to.ResourceTO;

public class SearchIndex {
	
	static final String LUCENE_INDEX_DIRECTORY = "C:\\lucene\\";
	
	public static ArrayList searchIndexData(String userQuery){
		
		IndexReader reader = null;
		IndexSearcher searcher = null;
		TopScoreDocCollector collector = null;
		Query query = null;
		ScoreDoc[] hits = null;
		ArrayList al = new ArrayList();
        ResourceTO to = null;
        int ResultsPerPage = 5;

		try{
			
			//create standard analyzer object
			Analyzer analyzer = new StandardAnalyzer(Version.LUCENE_30);
			//create File object of our index directory
			File file = new File(LUCENE_INDEX_DIRECTORY);
			//create index reader object
			reader = IndexReader.open(FSDirectory.open(file),true);
			//create index searcher object
			searcher = new IndexSearcher(reader);
			//create topscore document collector
			collector = TopScoreDocCollector.create(2*ResultsPerPage, false);
			
			//create query parser object
			QueryParser parser = new QueryParser(Version.LUCENE_30, "fulltext", analyzer);
			//parse the query and get reference to Query object
			query = parser.parse(userQuery);
			//search the query
			searcher.search(query, collector);
			hits = collector.topDocs().scoreDocs;
			
			//check whether the search returns any result
			if(hits.length>0){
				
				//iterate through the collection and display result
				for(int i=0; i<hits.length; i++){
					int scoreId = hits[i].doc;
					//now get reference to document
					Document document = searcher.doc(scoreId);
					to = new ResourceTO();
					to.setArticleId(Integer.parseInt(document.getField("id").stringValue()));
					to.setTitle(document.getField("title").stringValue());
					to.setPostDate(java.sql.Timestamp.valueOf(document.getField("post_date").stringValue()));
					al.add(to);
				}
			}
			
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			if(reader!=null)
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
		
		return al;
	}

}