-
Notifications
You must be signed in to change notification settings - Fork 0
/
easySearch.java
219 lines (154 loc) · 7.75 KB
/
easySearch.java
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Set;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Paths;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.LeafReaderContext;
import org.apache.lucene.index.MultiFields;
import org.apache.lucene.index.PostingsEnum;
import org.apache.lucene.index.Term;
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.similarities.ClassicSimilarity;
public class easySearch {
public void term(int totalLength, String queryString, IndexReader reader, IndexSearcher searcher) {
try {
// As given by the assign, call the standard analyzer
Analyzer analyzer = new StandardAnalyzer();
QueryParser parser = new QueryParser("TEXT", analyzer);
Query query = parser.parse(queryString);
Set<Term> queryTerms = new LinkedHashSet<Term>();
// extract terms
searcher.createNormalizedWeight(query, false).extractTerms(queryTerms);
for (Term t : queryTerms) {
//System.out.println(t.text());
// get frq for preparison of tfidf
int df=reader.docFreq(new Term("TEXT", t.text()));
//Use DefaultSimilarity.decodeNormValue(…) to decode normalized document length
ClassicSimilarity dSimi = new ClassicSimilarity();
// Get the segments of the index
List<LeafReaderContext> leafContexts = reader.getContext().reader().leaves();
HashMap storeMap = new HashMap();
double termSocre=0;
// Processing each segment
for (int i = 0; i < leafContexts.size(); i++) {
LeafReaderContext leafContext = leafContexts.get(i);
int startDocNo = leafContext.docBase;
int numberOfDoc = leafContext.reader().maxDoc();
// store docnum,freq pair into a hashmap
PostingsEnum de = MultiFields.getTermDocsEnum(leafContext.reader(), "TEXT", new BytesRef(t.text()));
int doc;
if (de != null) {
while ((doc = de.nextDoc()) != PostingsEnum.NO_MORE_DOCS) {
if(!storeMap.containsKey(de.docID()+startDocNo)){
storeMap.put(de.docID()+startDocNo, de.freq());
}
}
}
// count the occurance of terms in documents
// set the start docid to 0
for (int docId = 0; docId < numberOfDoc+0; docId++) {
//init occurance
int occurance=0;
// Get normalized length (1/sqrt(numOfTokens)) of the document
float normDocLeng = dSimi.decodeNormValue(leafContext.reader().getNormValues("TEXT").get(docId));
// Get the real length of the document
float realDocLength = 1 / (normDocLeng * normDocLeng);
if(storeMap.containsKey(docId + startDocNo)){
// convert to int for further tfidf caculation
occurance = (int) storeMap.get(docId + startDocNo);
}
//tfidf ranking function
termSocre = (occurance/realDocLength)*Math.log(1+(totalLength/df));
System.out.println( "For doc number " + searcher.doc(docId + startDocNo).get("DOCNO") + " : ");
System.out.println("Score on each term " + t.text() +" is " + termSocre);
}
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
public void totalquery(int totalLength, String queryString, IndexReader reader, IndexSearcher searcher) {
try {
// similiar to the each term function
Analyzer analyzer = new StandardAnalyzer();
QueryParser parser = new QueryParser("TEXT", analyzer);
Query query;
query = parser.parse(queryString);
Set<Term> queryTerms = new LinkedHashSet<Term>();
searcher.createNormalizedWeight(query, false).extractTerms(queryTerms);
ClassicSimilarity dSimi = new ClassicSimilarity();
List<LeafReaderContext> leafContexts = reader.getContext().reader().leaves();
double termSocre=0;
for (int i = 0; i < leafContexts.size(); i++) {
LeafReaderContext leafContext = leafContexts.get(i);
int startDocNo = leafContext.docBase;
int numberOfDoc = leafContext.reader().maxDoc();
for (int docId = 0; docId < numberOfDoc; docId++) {
// each term occurance in each doc
int occurance=0;
float normDocLeng = dSimi.decodeNormValue(leafContext.reader().getNormValues("TEXT").get(docId));
float realDocLeng = 1/(normDocLeng * normDocLeng);
// whole query
double queryScore=0;
for (Term t : queryTerms) {
int docIncludeTerm=reader.docFreq(new Term("TEXT", t.text()));
PostingsEnum p = MultiFields.getTermDocsEnum(leafContext.reader(), "TEXT", new BytesRef(t.text()));
int doc;
if (p != null) {
while ((doc = p.nextDoc()) != PostingsEnum.NO_MORE_DOCS) {
if(p.docID()+startDocNo == docId + startDocNo){
occurance = p.freq();
break;
}
}
}
//TFIDF
termSocre = (occurance/realDocLeng)*Math.log(1+(totalLength/docIncludeTerm));
// sum on each term
queryScore+=termSocre;
}
System.out.println( "For doc number " + searcher.doc(docId + startDocNo).get("DOCNO") + " : ");
System.out.println("Score on query " + queryString + " is " + queryScore);
}
}
}
catch(Exception e){
e.printStackTrace();
}
}
public static void main(String[] args) throws ParseException, IOException {
String indexpath = "index";
easySearch search = new easySearch();
IndexReader reader = DirectoryReader.open(FSDirectory.open(Paths.get(indexpath)));
IndexSearcher searcher = new IndexSearcher(reader);
String queryString = "the great wall";
int totalLength = reader.maxDoc();
// call the score on each term
search.term(totalLength, queryString, reader, searcher);
//call the score on total query
search.totalquery(totalLength, queryString, reader, searcher);
}
}