-
Notifications
You must be signed in to change notification settings - Fork 0
/
QryEval.java
275 lines (214 loc) · 7.81 KB
/
QryEval.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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
/*
* Copyright (c) 2016, Carnegie Mellon University. All Rights Reserved.
* Version 3.1.2.
*/
import java.io.*;
import java.util.*;
import org.apache.lucene.analysis.Analyzer.TokenStreamComponents;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.*;
import org.apache.lucene.search.*;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;
/**
* This software illustrates the architecture for the portion of a
* search engine that evaluates queries. It is a guide for class
* homework assignments, so it emphasizes simplicity over efficiency.
* It implements an unranked Boolean retrieval model, however it is
* easily extended to other retrieval models. For more information,
* see the ReadMe.txt file.
*/
public class QryEval {
// --------------- Constants and variables ---------------------
private static final String USAGE =
"Usage: java QryEval paramFile\n\n";
private static final String[] TEXT_FIELDS =
{ "body", "title", "url", "inlink" };
// --------------- Methods ---------------------------------------
/**
* @param args The only argument is the parameter file name.
* @throws Exception Error accessing the Lucene index.
*/
public static void main(String[] args) throws Exception {
// This is a timer that you may find useful. It is used here to
// time how long the entire program takes, but you can move it
// around to time specific parts of your code.
Timer timer = new Timer();
timer.start ();
// Check that a parameter file is included, and that the required
// parameters are present. Just store the parameters. They get
// processed later during initialization of different system
// components.
if (args.length < 1) {
throw new IllegalArgumentException (USAGE);
}
Map<String, String> parameters = readParameterFile (args[0]);
// Open the index and initialize the retrieval model.
Idx.open (parameters.get ("indexPath"));
RetrievalModel model = initializeRetrievalModel (parameters);
// Perform experiments.
processQueryFile(parameters.get("queryFilePath"), model);
// Clean up.
timer.stop ();
System.out.println ("Time: " + timer);
}
/**
* Allocate the retrieval model and initialize it using parameters
* from the parameter file.
* @return The initialized retrieval model
* @throws IOException Error accessing the Lucene index.
*/
private static RetrievalModel initializeRetrievalModel (Map<String, String> parameters)
throws IOException {
RetrievalModel model = null;
String modelString = parameters.get ("retrievalAlgorithm").toLowerCase();
if (modelString.equals("unrankedboolean")) {
model = new RetrievalModelUnrankedBoolean();
}
else {
throw new IllegalArgumentException
("Unknown retrieval model " + parameters.get("retrievalAlgorithm"));
}
return model;
}
/**
* Print a message indicating the amount of memory used. The caller can
* indicate whether garbage collection should be performed, which slows the
* program but reduces memory usage.
*
* @param gc
* If true, run the garbage collector before reporting.
*/
public static void printMemoryUsage(boolean gc) {
Runtime runtime = Runtime.getRuntime();
if (gc)
runtime.gc();
System.out.println("Memory used: "
+ ((runtime.totalMemory() - runtime.freeMemory()) / (1024L * 1024L)) + " MB");
}
/**
* Process one query.
* @param qString A string that contains a query.
* @param model The retrieval model determines how matching and scoring is done.
* @return Search results
* @throws IOException Error accessing the index
*/
static ScoreList processQuery(String qString, RetrievalModel model)
throws IOException {
String defaultOp = model.defaultQrySopName ();
qString = defaultOp + "(" + qString + ")";
Qry q = QryParser.getQuery (qString);
// Show the query that is evaluated
System.out.println(" --> " + q);
if (q != null) {
ScoreList r = new ScoreList ();
if (q.args.size () > 0) { // Ignore empty queries
q.initialize (model);
while (q.docIteratorHasMatch (model)) {
int docid = q.docIteratorGetMatch ();
double score = ((QrySop) q).getScore (model);
r.add (docid, score);
q.docIteratorAdvancePast (docid);
}
}
return r;
} else
return null;
}
/**
* Process the query file.
* @param queryFilePath
* @param model
* @throws IOException Error accessing the Lucene index.
*/
static void processQueryFile(String queryFilePath,
RetrievalModel model)
throws IOException {
BufferedReader input = null;
try {
String qLine = null;
input = new BufferedReader(new FileReader(queryFilePath));
// Each pass of the loop processes one query.
while ((qLine = input.readLine()) != null) {
int d = qLine.indexOf(':');
if (d < 0) {
throw new IllegalArgumentException
("Syntax error: Missing ':' in query line.");
}
printMemoryUsage(false);
String qid = qLine.substring(0, d);
String query = qLine.substring(d + 1);
System.out.println("Query " + qLine);
ScoreList r = null;
r = processQuery(query, model);
if (r != null) {
printResults(qid, r);
System.out.println();
}
}
} catch (IOException ex) {
ex.printStackTrace();
} finally {
input.close();
}
}
/**
* Print the query results.
*
* THIS IS NOT THE CORRECT OUTPUT FORMAT. YOU MUST CHANGE THIS METHOD SO
* THAT IT OUTPUTS IN THE FORMAT SPECIFIED IN THE HOMEWORK PAGE, WHICH IS:
*
* QueryID Q0 DocID Rank Score RunID
*
* @param queryName
* Original query.
* @param result
* A list of document ids and scores
* @throws IOException Error accessing the Lucene index.
*/
static void printResults(String queryName, ScoreList result) throws IOException {
System.out.println(queryName + ": ");
if (result.size() < 1) {
System.out.println("\tNo results.");
} else {
for (int i = 0; i < result.size(); i++) {
System.out.println("\t" + i + ": " + Idx.getExternalDocid(result.getDocid(i)) + ", "
+ result.getDocidScore(i));
}
}
}
/**
* Read the specified parameter file, and confirm that the required
* parameters are present. The parameters are returned in a
* HashMap. The caller (or its minions) are responsible for processing
* them.
* @return The parameters, in <key, value> format.
*/
private static Map<String, String> readParameterFile (String parameterFileName)
throws IOException {
Map<String, String> parameters = new HashMap<String, String>();
File parameterFile = new File (parameterFileName);
if (! parameterFile.canRead ()) {
throw new IllegalArgumentException
("Can't read " + parameterFileName);
}
Scanner scan = new Scanner(parameterFile);
String line = null;
do {
line = scan.nextLine();
String[] pair = line.split ("=");
parameters.put(pair[0].trim(), pair[1].trim());
} while (scan.hasNext());
scan.close();
if (! (parameters.containsKey ("indexPath") &&
parameters.containsKey ("queryFilePath") &&
parameters.containsKey ("trecEvalOutputPath") &&
parameters.containsKey ("retrievalAlgorithm"))) {
throw new IllegalArgumentException
("Required parameters were missing from the parameter file.");
}
return parameters;
}
}