WEBUS2.0 In Action - 创建索引
WEBUS2.0只能够将一种Document数据类型(Webus.Index.Document类)添加到索引中,所有其他类型的数据(如txt、html、word、pdf等等)都需要预先转换成Document才能够对其编制索引:
如此一来,对于新的数据类型,我们只要开发新的Parser就能够将其添加到索引中,因此WEBUS依靠这种方式获得了很高的通用性。
一个Document是多个Field(字段)的集合,每个Field主要包含Name和Value两个属性:
如果我们要将下表的数据添加到索引中,
代码如下:
1. 准备数据
string[] Titles = new string[] {
"A Modern Art of Education - Rudolf Steiner",
"Imperial Secrets of Health and Longevity - Bob Flaws",
"Tao Te Ching 道德经 - Stephen Mitchell",
"Godel, Escher, Bach: an Eternal Golden Braid - Douglas Hofstadter"
};
string[] Categories = new string[] {
"/education/pedagogy",
"/health/alternative/Chinese",
"/philsosphy/eastern",
"/technology/computers/ai"
};
string[] Subjects = new string[] {
"education philosophy psychology practice Waldorf",
"diet chinese medicine qi gong health herbs",
"taoism",
"artificial intelligence number theory mathematics music"
};
"A Modern Art of Education - Rudolf Steiner",
"Imperial Secrets of Health and Longevity - Bob Flaws",
"Tao Te Ching 道德经 - Stephen Mitchell",
"Godel, Escher, Bach: an Eternal Golden Braid - Douglas Hofstadter"
};
string[] Categories = new string[] {
"/education/pedagogy",
"/health/alternative/Chinese",
"/philsosphy/eastern",
"/technology/computers/ai"
};
string[] Subjects = new string[] {
"education philosophy psychology practice Waldorf",
"diet chinese medicine qi gong health herbs",
"taoism",
"artificial intelligence number theory mathematics music"
};
2. 添加索引
IIndexWriter writer = new IndexManager(new SimpleWordAnalyzer()); //用SimpleWordAnalyzer构造一个Index Writer
writer.New(@"F:\Index"); //在F:\Index目录新建索引
for (int i = 0; i < Titles.Length; i++)
{
Document doc = new Document();
doc.Fields.Add(new Field("Title", Titles[i], FieldAttributes.Index | FieldAttributes.Analyse));
doc.Fields.Add(new Field("Category", Categories[i], FieldAttributes.Index | FieldAttributes.Sort));
doc.Fields.Add(new Field("Subject", Subjects[i], FieldAttributes.Analyse | FieldAttributes.Index));
writer.Add(doc); //将Document添加到索引
}
writer.Close(); //保存并关闭索引
writer.New(@"F:\Index"); //在F:\Index目录新建索引
for (int i = 0; i < Titles.Length; i++)
{
Document doc = new Document();
doc.Fields.Add(new Field("Title", Titles[i], FieldAttributes.Index | FieldAttributes.Analyse));
doc.Fields.Add(new Field("Category", Categories[i], FieldAttributes.Index | FieldAttributes.Sort));
doc.Fields.Add(new Field("Subject", Subjects[i], FieldAttributes.Analyse | FieldAttributes.Index));
writer.Add(doc); //将Document添加到索引
}
writer.Close(); //保存并关闭索引
补充:关于FieldAttributes
在Field中还有另外一个属性即Attribute(FieldAttributes类型),它与数据无关,但是会直接影响编制索引的行为:
FieldAttributes.Index:需要编制索引
FieldAttributes.Analyse:需要经过分析
FieldAttributes.UnStore:字段值(Field.Value)将不会保存到索引中
FieldAttributes.Sort:需要排序,选择此项的字段在编制索引时将会排序
FieldAttributes.Compress:需要压缩,选择此项将用GZip压缩算法对字段值进行压缩
这5个属性可以组合使用,如FieldAttributes.Default就是一个组合属性,它等于FieldAttributes.Index | FieldAttributes.Sort 。
下一篇:WEBUS2.0 In Action - 开始搜索
相关信息及WEBUS2.0 SDK下载:继续我的代码,分享我的快乐 - WEBUS2.0