对于一项要求,我必须存储多对多关系的信息。 每个邮政编码都有N个courseIds,每个课程代码都有N个邮政编码。 我将此信息存储在 Lucene 版本6.4 中。
private static void updateDoc(IndexWriter w, String id, String zipCode, String courseId) throws IOException {
Term term = new Term("id", id);
Document doc = new Document();
doc.add(new StringField("id", id, Field.Store.YES));
doc.add(new StringField("zipCode", zipCode, Field.Store.YES));
doc.add(new StringField("courseName", courseId, Field.Store.YES));
w.updateDocument(term, doc);
}
public static void main(String[] args) throws Exception {
File dataDir = new File("E:/local/data/");
IndexWriter indexWriter = getIndexWriter(dataDir);
//Zip Code
for (int i = 0; i < 5; i++) {
String zipCode = String.format("%05d", i);
for (int j = 0; j < 10; j++) {
String courseCode = "Course" + String.format("%03d", j);
String id = getID();
System.out.println(zipCode + "<---->" + courseCode);
updateDoc(indexWriter, id, zipCode, courseCode);
}
}
try {
indexWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
但问题是在搜索时,我没有获得针对邮政编码的课程ID的点击。
对于以下代码,我得到了正确的结果。
String queryStr = "00003";//For zip code only
StandardAnalyzer analyzer = new StandardAnalyzer();
Query q = new QueryParser("zipCode", analyzer).parse(queryStr);
System.out.println(q.toString());
IndexSearcher searcher = getIndexSearcher();
TopDocs docs = searcher.search(q, 10);
System.out.println("Total :::" + docs.totalHits);
ScoreDoc[] hits = docs.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("id") + " " + d.get("zipCode") + "\t" + d.get("courseName"));
}
但是对于下面的代码,我没有得到结果,理想情况下它应该提供结果。我试图以与我为邮政编码类似的方式检索课程代码的结果。
String queryStr = "Course005";//For course code only
StandardAnalyzer analyzer = new StandardAnalyzer();
Query q = new QueryParser("courseName", analyzer).parse(queryStr);
System.out.println(q.toString());
IndexSearcher searcher = getIndexSearcher();
TopDocs docs = searcher.search(q, 10);
System.out.println("Total :::" + docs.totalHits);
ScoreDoc[] hits = docs.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("id") + " " + d.get("zipCode") + "\t" + d.get("courseName"));
}
如果你查看上面两个代码片段,两者都是相同的,但字段名称是不同的。
请帮助我理解并让我知道它为什么不起作用。 请通过仅传递查询字符串和字段名称来帮助如何实现结果。