solr and the use of solr net

solr and. net (5) the use of solrnet

Recently, due to the busy project, this article came out late. It has been half a month since the last article. In this lesson, we will learn solr net, solr's. Net client

Source: https://github.com/make/solrnet

The previous article described how C ා requests and accepts solr's data. The request link is spliced by itself, and the data contract is used to accept data. solrnet encapsulates these steps, so you can request and accept data by directly calling methods

First, download the DLL to be used by solrnet

     Microsoft.Practices.ServiceLocation.dll

     SolrNet.dll

     HttpWebAdapters.dll

Download address: http://pan.baidu.com/s/1pJt7Wr5

Create a project and reference the DLL above

OK, let's start the actual battle. Let's design a query condition title = "keyword" and (area = "Beijing" or area = "Shanghai") and industry = "power" and columns = "project" order time desc

(1) create an entity class to receive data as follows

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 corresponds to the unique key of solr, and SolrField corresponds to the received field

 

(2) create Global.asax and add the following code

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)
        {

        }
    }
}

Reference using SolrNet;

Startup. Init < article > ("http://192.168.0.14:8080/solr/collection1"); request the address of Solr server

(3) we start to use solrnet to create an aspx page. First, look at the code and then explain the meaning of each method

     

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("Shanghai", "Beijing,Shanghai", "power", "project", 1, "0");
          
        }

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




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

            //Establish sort, condition.
            QueryOptions options = new QueryOptions();
            options.Rows = pageNum;//Number of data
            options.Start = start;//Start item
        

            //Create query criteria
            var qTB = new SolrQueryByField("title", keyword);

            //Create condition set
            List<ISolrQuery> query = new List<ISolrQuery>();
            //Add condition
            query.Add(qTB);

            //Query region,Multiple regions,Here ,Number separated,Example: Beijing,Shanghai,Hangzhou
            if (area != "")
            {
                //Create a collective storage area
                List<ISolrQuery> ar = new List<ISolrQuery>();
                string[] ares = area.Split(new char[] { ',' });
                foreach (string a in ares)
                {
                    //Storage area
                    ar.Add(new SolrQueryByField("area", a));
                }
                //Create relationships between regions,yes OR still AND
                var qArea = new SolrMultipleCriteriaQuery(ar, "OR");
                //Add to condition set
                query.Add(qArea);
            }
            //Industry conditions,Same as region
            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);
            }
            //The column conditions are the same as above
            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);
            }

            //Create time range instance
            SolrQueryByRange<DateTime> qDateRange = null;
            //Data in seven days
            if (time == "-7")
            {
                //The last two parameters,One is the start time,One is the end time
                qDateRange = new SolrQueryByRange<DateTime>("adddate", DateTime.Now.AddDays(int.Parse(time)), DateTime.MaxValue);
            }
            else if (time == "0")//All data
            {
                qDateRange = new SolrQueryByRange<DateTime>("adddate", DateTime.MinValue, DateTime.MaxValue);
            }
            else//Other
            {
                qDateRange = new SolrQueryByRange<DateTime>("adddate", DateTime.Today.AddMonths(int.Parse(time)), DateTime.MaxValue);
            }

            //Join collection
            query.Add(qDateRange);


            //Reverse by time.
            options.AddOrder(new SolrNet.SortOrder("adddate", Order.DESC));


            //Relationship between condition sets
            var qTBO = new SolrMultipleCriteriaQuery(query, "AND");

            //Execute query,There are 5 overloads
            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;
                //row["body"] = OptimizeHighlight(body, keyword);
                row["addDate"] = article.adddate.ToShortDateString();
                row["url"] = url;

                this.Result.Rows.Add(row);
            }

        }
    }
}

Let's analyze the above code in a paragraph

Create a solr instance, and finally use this to execute the command

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

Define parameters, sort, highlight, start item, number of pages

     

QueryOptions options = new QueryOptions();

     options.Rows = pageNum;//Number of data

     options.Start = start;//Start item

Next, create the query criteria. First, create the add set

List<ISolrQuery> query = new List<ISolrQuery>();

Start to create a condition and add it to the collection, which is a simple condition

//Create query criteria
            var qTB = new SolrQueryByField("title", keyword);
             //Add condition
            query.Add(qTB);

Add a slightly complex condition below, such as selecting a region in Beijing OR Shanghai

//Query region,Multiple regions,Here ,Number separated,Example: Beijing,Shanghai,Hangzhou
            if (area != "")
            {
                //Create a collective storage area
                List<ISolrQuery> ar = new List<ISolrQuery>();
                string[] ares = area.Split(new char[] { ',' });
                foreach (string a in ares)
                {
                    //Storage area
                    ar.Add(new SolrQueryByField("area", a));
                }
                //Create relationships between regions,yes OR still AND
                var qArea = new SolrMultipleCriteriaQuery(ar, "OR");
                //Add to condition set
                query.Add(qArea);
            }
            //Industry conditions,Same as region
            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);
            }
           //The column conditions are the same as above
            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);
            }

Add time range and add condition set

//Create time range instance
            SolrQueryByRange<DateTime> qDateRange = null;
            //Data in seven days
            if (time == "-7")
            {
                //The last two parameters,One is the start time,One is the end time
                qDateRange = new SolrQueryByRange<DateTime>("adddate", DateTime.Now.AddDays(int.Parse(time)), DateTime.MaxValue);
            }
            else if (time == "0")//All data
            {
                qDateRange = new SolrQueryByRange<DateTime>("adddate", DateTime.MinValue, DateTime.MaxValue);
            }
            else//Other
            {
                qDateRange = new SolrQueryByRange<DateTime>("adddate", DateTime.Today.AddMonths(int.Parse(time)), DateTime.MaxValue);
            }

            //Join collection
            query.Add(qDateRange);

Determines the relationship between existing conditions in a set, AND OR

var qTBO = new SolrMultipleCriteriaQuery(query, "AND");

Execute query to get results

//Execute query,There are 5 overloads
     SolrQueryResults<Article> results = solr.Query(qTBO, options);

Next, let's run it to see if we accept the imported data

    

 

After running the program, 36 pieces of data are obtained, which indicates that solrnet is running successfully. Here are just some basic query methods. To understand all the methods, you can go to the official website to view them

Address: https://github.com/march/solrnet/blob/master/documentation/querying.md

solrnet can also insert data into solr, which is very simple. Just call the add (entity) method directly

Example: solr.add(Article);

This is the end of this section. In the next section, we will talk about the timing incremental index of solr and the security of solr

Here we recommend another solr. net client EastNet.Solr

       http://www.cnblogs.com/TerryLiang/archive/2011/05/03/2034847.html

qq group: 424259523

Tags: solr github

Posted on Sun, 03 May 2020 19:23:34 -0400 by coltrane