要想成就一个伟人,不仅要有聪明的头脑,还要有执着的信念,滴水穿石的雄心。
Product.cs实体类:
public class Product
{
private int _id;
public int Id
{
get { return _id; }
set { _id = value; }
}
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
public Product() { }
public Product(int id,string name)
{
this.Id = id;
this.Name = name;
}
}
ProductDAL.cs代码:
public static class ProductDAL
{
public static List GetProductInfo()
{
List list = new List();
for (int i = 1; i <= 100;i++ )
{
Product product = new Product(i,"商品"+i.ToString());
list.Add(product);
}
return list;
}
}
ProductBLL.cs代码:
public static class ProductBLL
{
public static List GetProductInfo()
{
return ProductDAL.GetProductInfo();
}
}
CreateLucene.cs代码:
public class CreateLucene
{
public CreateLucene()
{
}
public static void CreateIndex(List list)
{
Analyzer analyzer = new StandardAnalyzer();
IndexWriter indexwriter = new IndexWriter("All_Product", analyzer, true);
for (int i = 0, count = list.Count; i < count;i++ )
{
Product product=list[i];
Document document = new Document();
document.Add(new Field("productId",product.Id.ToString(),Field.Store.YES,Field.Index.TOKENIZED));
document.Add(new Field("productName",product.Name,Field.Store.YES,Field.Index.TOKENIZED));
indexwriter.AddDocument(document);
}
indexwriter.Optimize();
indexwriter.Close();
}
}
SearchProduct.cs代码:
public class SearchProduct
{
public SearchProduct()
{ }
public static List SearchProductInfo(string key)
{
Analyzer analyzer = new StandardAnalyzer();
List list = new List();
IndexSearcher indexsearcher = new IndexSearcher("All_Product");
QueryParser queryParser = new QueryParser("productName", analyzer);
Query query = queryParser.Parse(key);
Hits hits = indexsearcher.Search(query);
if (hits.Length() > 0)
{
for (int i = 0, count = hits.Length(); i < count;i++ )
{
Document document = hits.Doc(i);
Product product = new Product();
product.Id =Convert.ToInt32(document.Get("productId"));
product.Name = document.Get("productName");
list.Add(product);
}
}
indexsearcher.Close();
return list;
}
}
Global.asax内容:
showproduct.aspx.cs
public partial class _Default : System.Web.UI.Page
{
private string NameKey
{
get
{
if (this.Request["txtNameKey"] != null)
{
return this.Request["txtNameKey"];
}
return "";
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected List GetProductInfo()
{
List list = new List();
if (this.NameKey != "")
{
list = SearchProduct.SearchProductInfo(this.NameKey);
}
return list;
}
}
showproduct.aspx的内容
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>无标题页title>
head>
<body>
<form id="form1" method="post" action="showproduct.aspx">
<div>
<input type="text" name="txtNameKey" /><input type="submit" value="搜索" />
div>
form>
<hr />
<div>
<h2>
信息显示
h2>
div>
<div>
<%
List list = base.GetProductInfo();
if (list != null && list.Count != 0)
{
foreach (Product pro in list)
{
%>
<%=pro.Id%>,<%=pro.Name%><br />
<%
}
}
%>
div>
body>
html>
外部DLL引用如图:
Lucene.Net点击下载
运行结果如图:
