Lucene.net实现搜索

Lucene.net+博客园程序中提取出来的Lucene.Net.Analysis.Cn.dll来实现中文分词

引用Lucene.Net.Analysis.Cn.dll和Lucene.Net.dll

VS2010实现

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Lucene.Net.Analysis;
using Lucene.Net;
using Lucene.Net.Index;
using Lucene.Net.Store;
using Lucene.Net.Analysis.Cn;
using Lucene.Net.Documents;
using Lucene.Net.QueryParsers;
using Lucene.Net.Search;
using Lucene.Net.Util;
namespace SearchEngine
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        IndexSearcher searcher;
        private void btnIndexWrite_Click(object sender, EventArgs e)
        {
            RAMDirectory ramDirectory = new Lucene.Net.Store.RAMDirectory();
            IndexWriter ramWriter = new IndexWriter(ramDirectory, new ChineseAnalyzer(), true);
            string[] words = { "中华人民共和国", "人民共和国", "人民", "共和国" };
            Document doc = null;
            foreach (var word in words)
            {
                doc = new Document();
                doc.Add(Field.Text("contents",word));
                doc.Add(Field.Text("Uri", "http://123"));
                doc.Add(Field.Text("Title", word));
                doc.Add(Field.Text("CreateTime", DateTime.Now.ToString("yyyy-MM-dd")));
                doc.Add(Field.Text("Summary", "zhenshi" ));
                ramWriter.AddDocument(doc);


            }
            ramWriter.Optimize();
            ramWriter.Close();
            searcher = new IndexSearcher(ramDirectory);






        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            
            string pattern = tbWord.Text;
            if (string.IsNullOrEmpty(pattern))
                return;
            Query query = QueryParser.Parse(pattern, "contents", new ChineseAnalyzer());

            //获取搜索结果
            Hits hits = searcher.Search(query);

            //判断是否有搜索到的结果,当然你也可以遍历结果集并输出
            if (hits.Length() != 0)
            {
                MessageBox.Show("有");
                for (int i = 0; i < hits.Length(); i++)
                {
                    Document doc = hits.Doc(i);
                    string aa=string.Format("title:{0},url:{1},time:{2}\n", doc.Get("Title"),doc.Get("Uri"), doc.Get("CreateTime"));
                    tbResult.Text += aa;
                }

            }
            else
                MessageBox.Show("没有");
            searcher.Close();

        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值