Lucene.NET使用入门(一)【实现快速搜索】

要想成就一个伟人,不仅要有聪明的头脑,还要有执着的信念,滴水穿石的雄心。

Product.cs实体类:

 /// <summary>
    /// 商品类
    /// </summary>
    public class Product
    {
        /// <summary>
        /// 商品编号
        /// </summary>
        private int _id;

        public int Id
        {
            get { return _id; }
            set { _id = value; }
        }
        /// <summary>
        /// 商品名称
        /// </summary>
        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
    {
        /// <summary>
        ///取出所有的商品
        /// </summary>
        /// <returns>商品集合</returns>
        public static List<Product> GetProductInfo()
        {
            List<Product> list = new List<Product>();
            //连接数据库
            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
    {
        /// <summary>
        /// 取出所有的商品
        /// </summary>
        /// <returns>商品集合</returns>
        public static List<Product> GetProductInfo()
        {
            return ProductDAL.GetProductInfo();
        }
    }

CreateLucene.cs代码:

/// <summary>
/// CreateIndex 的摘要说明
/// </summary>
public class CreateLucene
{
    public CreateLucene()
    {
        //
        // TODO: 在此处添加构造函数逻辑
        //
    }
    /// <summary>
    /// 创建索引
    /// </summary>
    /// <param name="list">商品集合</param>
    public static void CreateIndex(List<Product> 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代码:

/// <summary>
/// SearchProduct 的摘要说明
/// </summary>
public class SearchProduct
{
    public SearchProduct()
    { }
    public static List<Product> SearchProductInfo(string key)
    {
        Analyzer analyzer = new StandardAnalyzer();
        List<Product> list = new List<Product>();

        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内容:

<script runat="server">

    void Application_Start(object sender, EventArgs e) 
    {
        // 在应用程序启动时运行的代码
        List<Product> list = ProductBLL.GetProductInfo();
        CreateLucene.CreateIndex(list); 
    }

    void Application_End(object sender, EventArgs e) 
    {
        //  在应用程序关闭时运行的代码

    }

    void Application_Error(object sender, EventArgs e) 
    { 
        // 在出现未处理的错误时运行的代码

    }

    void Session_Start(object sender, EventArgs e) 
    {
        // 在新会话启动时运行的代码

    }

    void Session_End(object sender, EventArgs e) 
    {
        // 在会话结束时运行的代码。 
        // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
        // InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer 
        // 或 SQLServer,则不会引发该事件。

    }     
</script>

showproduct.aspx.cs

//此处用到的也是标准分词,调用盘古分词搜索的体验会更好些
public partial class _Default : System.Web.UI.Page 
{
    /// <summary>
    /// 商品名称关键字
    /// </summary>
    private string NameKey
    {
        get
        {
            if (this.Request["txtNameKey"] != null)
            {
                return this.Request["txtNameKey"];
            }
            return "";
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    /// <summary>
    /// 得到商品集合
    /// </summary>
    /// <returns>商品集合</returns>
    protected List<Product> GetProductInfo()
    {
        List<Product> list = new List<Product>();
        if (this.NameKey != "")
        {
            list = SearchProduct.SearchProductInfo(this.NameKey);
        }

        return list;
    }
}

showproduct.aspx的内容

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<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<Product> 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点击下载

运行结果如图:

这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值