solr与.net系列课程(五)solrnet的使用

 solr与.net系列课程(五)solrnet的使用

     最近因项目比较忙,所以这篇文章出的比较晚,离上一篇文章已经有半个月的时间了,这节课我们来学下一下solr的.net客户端solrnet

     出处  https://github.com/mausch/SolrNet

    上一篇文章讲述了C#是如何请求和接受solr的数据的,请求链接是自己拼接的,接受数据是使用数据契约,solrnet就是把这些步骤封装起来,大家直接调用方法就可以请求和接受数据

     首先要下载solrnet所要使用的DLL

     Microsoft.Practices.ServiceLocation.dll

     SolrNet.dll

     HttpWebAdapters.dll

     下载地址 http://pan.baidu.com/s/1pJt7Wr5

     创建一个项目,然后引用上面的DLL

     好了,下面就开始实战, 我们来设计一个查询条件 title="关键字" and (area="北京" or area="上海") and industry="电力" and columns="项目" order time desc

     (1)创建一个接收数据的实体类,内容如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SolrNet.Attributes;

namespace WebApplication5
{
    public class Article
    {
        [SolrUniqueKey("id")]
        public int id { get; set; }

        [SolrField("title")]
        public string title { get; set; }

        [SolrField("area")]
        public string area { get; set; }

        [SolrField("industry")]
        public string industry { get; set; }

        [SolrField("body")]
        public string body { get; set; }

        [SolrField("adddate")]
        public DateTime adddate { get; set; }

        [SolrField("columns")]
        public string columns { get; set; }

        [SolrField("sorts")]
        public string sorts { get; set; }

        [SolrField("url")]
        public string url { get; set; }

        [SolrField("orderColumn")]
        public string orderColumn { get; set; }
    }
}

          SolrUniqueKey对应solr的唯一键,SolrField对应接收的字段

        (2) 创建Global.asax加入如下代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using SolrNet;

namespace WebApplication5
{
    public class Global : System.Web.HttpApplication
    {

        protected void Application_Start(object sender, EventArgs e)
        {
            Startup.Init<Article>("http://192.168.0.14:8080/solr/collection1");

        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }
    }
}

        引用using SolrNet;

        Startup.Init<Article>("http://192.168.0.14:8080/solr/collection1"); 请求solr服务器的地址

      (3)我们开始使用solrnet,创建一个aspx页面,先看代码在然后再解释每个方法的含义

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using SolrNet;
using SolrNet.Commands.Parameters;
using System.Text;
using System.Data;
using System.Text.RegularExpressions;
using Microsoft.Practices.ServiceLocation;

namespace WebApplication5
{
    public partial class _Default : System.Web.UI.Page
    {
        public DataTable Result = new DataTable();
        public int total;
        public int maxNum;
        public int pageNum = 36;
        protected void Page_Load(object sender, EventArgs e)
        {

            Search("上海", "北京,上海", "电力", "项目", 1, "0");
          
        }

        public void Search(string keyword, string area, string industry, string columns, int start, string time)
        {




            //定义solr
            ISolrOperations<Article> solr = ServiceLocator.Current.GetInstance<ISolrOperations<Article>>();

            //建立排序,条件.
            QueryOptions options = new QueryOptions();
            options.Rows = pageNum;//数据条数
            options.Start = start;//开始项
        

            //创建查询条件
            var qTB = new SolrQueryByField("title", keyword);

            //创建条件集合
            List<ISolrQuery> query = new List<ISolrQuery>();
            //添加条件
            query.Add(qTB);

            //查询地区,多个地区,这里用 ,号隔开,例 北京,上海,杭州
            if (area != "")
            {
                //创建集合存存储地区
                List<ISolrQuery> ar = new List<ISolrQuery>();
                string[] ares = area.Split(new char[] { ‘,‘ });
                foreach (string a in ares)
                {
                    //存储地区
                    ar.Add(new SolrQueryByField("area", a));
                }
                //创建地区之间的关系,是OR还是AND
                var qArea = new SolrMultipleCriteriaQuery(ar, "OR");
                //添加至条件集合
                query.Add(qArea);
            }
            //行业条件,与地区一样
            if (industry != "")
            {
                List<ISolrQuery> ind = new List<ISolrQuery>();
                string[] industs = industry.Split(new char[] { ‘,‘ });
                foreach (string a in industs)
                {
                    ind.Add(new SolrQueryByField("industry", a));
                }
                var qIndustry = new SolrMultipleCriteriaQuery(ind, "OR");
                query.Add(qIndustry);
            }
            //栏目条件同上
            if (columns != "")
            {
                List<ISolrQuery> colm = new List<ISolrQuery>();
                string[] cols = columns.Split(new char[] { ‘,‘ });
                foreach (string a in cols)
                {
                    colm.Add(new SolrQueryByField("columns", a));
                }
                var qColumns = new SolrMultipleCriteriaQuery(colm, "OR");
                query.Add(qColumns);
            }

            //创建时间范围实例
            SolrQueryByRange<DateTime> qDateRange = null;
            //七天内数据
            if (time == "-7")
            {
                //后两个参数,一个是开始时间,一个是结束时时间
                qDateRange = new SolrQueryByRange<DateTime>("adddate", DateTime.Now.AddDays(int.Parse(time)), DateTime.MaxValue);
            }
            else if (time == "0")//所有数据
            {
                qDateRange = new SolrQueryByRange<DateTime>("adddate", DateTime.MinValue, DateTime.MaxValue);
            }
            else//其他
            {
                qDateRange = new SolrQueryByRange<DateTime>("adddate", DateTime.Today.AddMonths(int.Parse(time)), DateTime.MaxValue);
            }

            //加入集合
            query.Add(qDateRange);


            //按照时间倒排序.
            options.AddOrder(new SolrNet.SortOrder("adddate", Order.DESC));


            //条件集合之间的关系
            var qTBO = new SolrMultipleCriteriaQuery(query, "AND");

            //执行查询,有5个重载
            SolrQueryResults<Article> results = solr.Query(qTBO, options);

            this.total = results.NumFound;
            maxNum = total / pageNum + 1;

            //Response.Write(t.Count);

            Result.Columns.Add("id", typeof(string));
            Result.Columns.Add("title", typeof(string));
            Result.Columns.Add("columns", typeof(string));
            Result.Columns.Add("orderColumn", typeof(string));
            Result.Columns.Add("area", typeof(string));
            Result.Columns.Add("industry", typeof(string));
            //Result.Columns.Add("body", typeof(string));
            Result.Columns.Add("addDate", typeof(string));
            Result.Columns.Add("url", typeof(string));

            foreach (Article article in results)
            {
                string id = article.id.ToString();
                string title = article.title;
                string orderColumn = article.orderColumn;
                string url = "";
                DataRow row = this.Result.NewRow();
                row["id"] = id;
                row["title"] = title;
                row["orderColumn"] = article.orderColumn;
                row["area"] = article.area;
                row["industry"] = article.industry;

相关推荐