简介:
Lucene是apache软件基金会4 jakarta项目组的一个子项目,是一个开放源代码的全文检索引擎工具包,即它不是一个完整的全文检索引擎,而是一个全文检索引擎的架构,提供了完整的查询引擎和索引引擎,部分文本分析引擎(英文与德文两种西方语言)。Lucene的目的是为软件开发人员提供一个简单易用的工具包,以方便的在目标系统中实现全文检索的功能,或者是以此为基础建立起完整的全文检索引擎。
作为一个开放源代码项目,Lucene从问世之后,引发了开放源代码社群的巨大反响,程序员们不仅使用它构建具体的全文检索应用,而且将之集成到各种系统软件中去,以及构建Web应用,甚至某些商业软件也采用了Lucene作为其内部全文检索子系统的核心。
Lucene是一个高性能、可伸缩的信息搜索(IR)库。它可以为你的应用程序添加索引和搜索能力。Lucene是用java实现的、成熟的开源项目,是 著名的Apache Jakarta大家庭的一员,并且基于Apache软件许可 [ASF, License]。同样,Lucene是目前非常流行的、免费的Java信息搜索(IR)库。
下面是用C#语言实现Lucene-文本检索的类,直接调用即可实现创建索引和文本检索
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections;
using Lucene.Net;
using Lucene.Net.Store;
using Lucene.Net.Index;
using Lucene.Net.Analysis.Standard;
using Lucene.Net.Documents;
using Lucene.Net.Search;
namespace LuceneDemo
{
class Lucene
{
public bool CreateIndexFile(ArrayList resourceList, string filePath)
{
try
{
//1、定义索引文件路径
FSDirectory ramdir = FSDirectory.GetDirectory(filePath);
IndexWriter ramwriter = new IndexWriter(ramdir, new StandardAnalyzer(), true,
IndexWriter.MaxFieldLength.UNLIMITED);
Console.WriteLine("开始生成索引文件");
//2、生索引文件);
//其中LuceneResourceInfo 是要存储的对象
foreach (LuceneResourceInfo lri in resourceList)
{
Document document = new Document();
//***
//说明:这里的Name,Phone,Address 是要存储对象的字段在索引里的命名,检索时可以根据任何一个字段进行检索
//**
document.Add(new Field("Name", lri.name, Field.Store.YES, Field.Index.ANALYZED,
Field.TermVector.YES));
document.Add(new Field("Phone", lri.phoneNo, Field.Store.YES, Field.Index.ANALYZED,
Field.TermVector.YES));
document.Add(new Field("Address", lri.address, Field.Store.YES, Field.Index.ANALYZED,
Field.TermVector.YES));
ramwriter.AddDocument(document);
}
ramwriter.Optimize();
ramwriter.Close();
Console.WriteLine("索引文件已生成");
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex);
return false;
}
}
//查询索引
public List<LuceneResourceInfo> Qury(string resourceName, string filePath)
{
List<LuceneResourceInfo> luceneResourceInfos = new List<LuceneResourceInfo>();
IndexSearcher searcher = new IndexSearcher(filePath);
//根据Name字段来查询
Query query = new TermQuery(new Term("Name", resourceName));//单个字节查询
Hits hits = searcher.Search(query);
for (int i = 0; i < hits.Length(); i++)
{
Document d = hits.Doc(i);
string name = d.Get("Name");
string phone = d.Get("Phone");
string address = d.Get("Address");
//存储的对象
LuceneResourceInfo info = new LuceneResourceInfo();
info.name = name;
info.phoneNo = phone;
info.address = address;
luceneResourceInfos.Add(info);
}
return luceneResourceInfos;
}
}
}
注:附件中有项目源码
第二个demo中包含模糊搜索和条件搜索两种,第一个demo中只有条件搜索