我正在尝试找到关于索引查询以下模型的解决方案: 学生有很多课程,每节课有一个年级。但是,课程成绩是关键值对。
我的第一个问题是:
我应该如何在lucene中索引keyvalue数据? (就像一个 坐标可能是空间的?)
第二个是
假设我在lucene中有一个索引数据。我怎样才能查询学生 课程名称,但按年级排序。
Student | Lesson | Grade
----------------------------
John | Math | A
John | Chemistry | C
Julie | Math | F
Julie | Chemistry | A
我可以创建一个类似的查询'从学生中选择课程=数学顺序按年级'sql短语
答案 0 :(得分:2)
在Lucene中,您索引索引中的文档,文档中包含字段。
在您的情况下,您将拥有一个包含3个字段的文档:学生,课程和成绩。然后使用这些文档填充索引。
小例子:
RAMDirectory ramDir = new RAMDirectory();
IndexWriter writer = new IndexWriter(ramDir, new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29));
Document doc = new Document();
Field studentName = new Field("student", "", Field.Store.YES, Field.Index.ANALYZED);
Field lesson = new Field("lesson", "", Field.Store.YES, Field.Index.ANALYZED);
Field grade = new Field("grade","", Field.Store.YES, Field.Index.NOT_ANALYZED);
doc.Add(studentName);
doc.Add(lesson);
doc.Add(grade);
studentName.SetValue("John");
lesson.SetValue("Math");
grade.SetValue("A");
writer.AddDocument(doc);
studentName.SetValue("John");
lesson.SetValue("Chemistry");
grade.SetValue("C");
writer.AddDocument(doc);
studentName.SetValue("Julie");
lesson.SetValue("Math");
grade.SetValue("F");
writer.AddDocument(doc);
studentName.SetValue("Julie");
lesson.SetValue("Chemistry");
grade.SetValue("A");
writer.AddDocument(doc);
writer.Commit();
IndexReader reader = writer.GetReader();
IndexSearcher searcher = new IndexSearcher(reader);
PerFieldAnalyzerWrapper aw = new PerFieldAnalyzerWrapper(new StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29));
aw.AddAnalyzer("grade", new KeywordAnalyzer());
Sort sort = new Sort(new SortField("grade", SortField.STRING));
QueryParser qp = new QueryParser(Lucene.Net.Util.Version.LUCENE_29, "lesson", aw);
Query q = qp.Parse("chemistry");
TopDocs docs = searcher.Search(q, null, 100, sort);
foreach (var scoreDoc in docs.ScoreDocs)
{
Console.WriteLine("Student: {0}; Lesson: {1}; Grade:{2}",
searcher.Doc(scoreDoc.doc).GetField("student").StringValue(),
searcher.Doc(scoreDoc.doc).GetField("lesson").StringValue(),
searcher.Doc(scoreDoc.doc).GetField("grade").StringValue());
}
Console.WriteLine("");
Console.WriteLine("---");
Console.WriteLine("");
q = qp.Parse("Math");
docs = searcher.Search(q, null, 100, sort);
foreach (var scoreDoc in docs.ScoreDocs)
{
Console.WriteLine("Student: {0}; Lesson: {1}; Grade:{2}",
searcher.Doc(scoreDoc.doc).GetField("student").StringValue(),
searcher.Doc(scoreDoc.doc).GetField("lesson").StringValue(),
searcher.Doc(scoreDoc.doc).GetField("grade").StringValue());
}
Console.Read();
reader.Close();
searcher.Close();
writer.Close();
打印:
Student: Julie; Lesson: Chemistry; Grade:A
Student: John; Lesson: Chemistry; Grade:C
---
Student: John; Lesson: Math; Grade:A
Student: Julie; Lesson: Math; Grade:F