Solr.net Use instance Tutorial

Source: Internet
Author: User
Tags foreach datetime solr solr query


profile Solr

Solr is a high-performance, JAVA5 development, SOLR based on Lucene's Full-text search server. At the same time, it has been extended to provide a richer query language than Lucene, while achieving configurable, scalable and optimized query performance, and provides a complete functional management interface, is a very good full-text search engine, He is based on the packaging of Lucene more mature Full-text Search server. How SOLR is deployed on a Windows server, recommend a letter peak blog http://www.cnblogs.com/wenxinghaha/tag/.net%20%20solr/, he wrote here in more detail. SOLR's 5.0 does not currently support IK participle, so it has to use version 4.10, and SOLR's deployment is also more convenient, with the time to deploy the database to the SOLR server through the configuration file, and to synchronize the data to the SOLR server based on the timing of the index.

SOLR is in. NET driver

The time we are doing the query is in the C # language used, so we need to use SOLR in. NET driver, is currently more popular with SOLR. NET and EASYNET.SOLR,SOLR. NET is a relatively stable open source of Solr Drive, EASYNET.SOLR is a domestic peer in the solr.net above done the package, I used the most original solr.net, driving the download address Https://github.com/mausch/SolrNet. Because the SOLR server is an operation that provides the RESTful interface, the solrnet request for the SOLR service is actually a

solrnet application based on the HTTP request

The application of solrnet I'm going to do a lot of explaining, and I'm here to say a few words. solrnet Group Query

with code


public class SolrNetOperate
{
    static SolrNetOperate ()
    {
        Startup.Init <LogItems> ("http://000.000.000.000:8080/solr/logs");
    }
    /// <summary>
    /// </summary>
    /// <param name = "dictPars"> Query parameter dictionary </ param>
    /// <param name = "start"> pagination tag </ param>
    /// <param name = "rows"> Number of pages </ param>
    /// <param name = "startTime"> start time </ param>
    /// <param name = "endTime"> end time </ param>
    /// <param name = "count"> Total number of output parameters </ param>
    /// <returns></returns>
    /// <remarks> oldman July 23, 2015 14:11:43 </ remarks>
    public static List <int> GroupingSerach (Dictionary <string, string> dictPars, int start, int rows,
        DateTime startTime, DateTime endTime, out int count)
    {
        // define solr
        var solr = ServiceLocator.Current.GetInstance <ISolrOperations <LogItems >> ();
        var queryOptions = new QueryOptions ();
        // define grouping
        var groupingParameters = new GroupingParameters ();
        groupingParameters.Fields = new Collection <string> {"logs_id"};
        groupingParameters.Ngroups = true; // Set the total number of query groups to true
        // define the filter conditions
        var timeRange = new SolrQueryByRange <DateTime> ("logs_time", startTime, endTime);
        queryOptions.AddFilterQueries (timeRange);
        foreach (string key in dictPars.Keys)
        {
            queryOptions.AddFilterQueries (new SolrQueryByField (key, dictPars [key]));
        }
        // define sort
        queryOptions.OrderBy = new Collection <SortOrder> {new SortOrder ("logs_id", Order.DESC)};
        queryOptions.Grouping = groupingParameters;
        queryOptions.Start = start;
        queryOptions.Rows = rows;
        SolrQueryResults <LogItems> res = solr.Query (SolrQuery.All, queryOptions);
        GroupedResults <LogItems> items = res.Grouping ["logs_id"];
        count = items.Ngroups ?? 0;
        return items.Groups.Select (item => Convert.ToInt32 (item.GroupValue)). ToList ();
    }
}



Here is the grouping to do the query, sorting and paging, the code is very clear.












Solrnet Tutorial




Basic usage of solrnet

http://code.google.com/p/solrnet/

First, we must generate a class to map the Solr field, and here is the map of the SOLR default schema:




public class Product {
[Solruniquekey (' ID ')] public
string ID {get; set;}
[Solrfield ("Manu_exact")]
public string manufacturer {get; set;}
[Solrfield ("Cat")] public
icollection<string> Categories {get; set;}
[Solrfield ("Price")]
Public decimal price {get; set;}
[Solrfield ("Instock")] public
bool Instock {get; set;}
}




Second, initialization:

[Testfixturesetup]




public void Fixturesetup () {
startup.init<product> ("HTTP://LOCALHOST:8983/SOLR");
}




Third. inclusion of the document (ensure that SOLR instance is running):

[Test]






public void Add() {
    var p = new Product {
        Id = "SP2514N",
        Manufacturer = "Samsung Electronics Co. Ltd.",
        Categories = new[] {
            "electronics",
            "hard drive",
        },
        Price = 92,
        InStock = true,
    };
var solr = ServiceLocator.Current.GetInstance<ISolrOperations<Product>>();
    solr.Add(p).Commit();
}




Fourth. Query Document Location:

[Test]




public void Query () {
var solr = servicelocator.current.getinstance<isolroperations<product>> ();
var results = Solr.    Query (New Solrquerybyfield ("id", "sp2514n"));
Assert.AreEqual (1, results.    Count);
Console.WriteLine (Results[0]. manufacturer);
}





Detailed tutorials

First, mapping

There are three ways of mapping:

1. Attributes (default)

With this method you decorate the properties of the want to map with the Solrfield and Solruniquekey attributes. The attribute parameter indicates the corresponding SOLR field name.

Example:




public class Product {
    [SolrUniqueKey("id")]
    public string Id { get; set; }
 
    [SolrField("manu_exact")]
    public string Manufacturer { get; set; }
 
    [SolrField("cat")]
    public ICollection<string> Categories { get; set; }
 
    [SolrField("price")]
    public decimal Price { get; set; }
 
    [SolrField("inStock")]
    public bool InStock { get; set; }
 
    [SolrField("timestamp")]
    public DateTime Timestamp { get; set; }
 
    [SolrField("weight")]
    public double? Weight { get; set;}
}




This way of mapping is implemented by the Attributesmappingmanager class.


2.     all-properties

This maps the ' class to a The field of the exact same name as the (note that SOLR field names are case-sensitive). It ' s implemented by the Allpropertiesmappingmanager class. Note that the unique keys cannot be inferred, and therefore have to be explicitly mapped. The same mapping as above could is accomplished like this:






public class Product {
    public string id { get; set; }
    public string manu_exact { get; set; }
    public ICollection<string> cat { get; set; }
    public decimal price { get; set; }
    public bool inStock { get; set; }
    public DateTime timestamp { get; set; }
    public double? weight { get; set; }
}
Then to add the unique key:
var mapper = new AllPropertiesMappingManager();
mapper.SetUniqueKey(typeof(Product).GetProperty("id"));




3.     Manual mapping

This allows your to programmatically Define the field for each property:




public class Product {
    public string Id { get; set; }
    public string Manufacturer { get; set; }
    public ICollection<string> Categories { get; set; }
    public decimal Price { get; set; }
    public bool InStock { get; set; }
    public DateTime Timestamp { get; set; }
    public double? Weight { get; set; }
}
var mgr = new MappingManager();
var property = typeof (Product).GetProperty("Id");
mgr.Add(property, "id");
mgr.SetUniqueKey(property);
mgr.Add(typeof(Product).GetProperty("Manufacturer"), "manu_exact");
mgr.Add(typeof(Product).GetProperty("Categories"), "cat_exact");
mgr.Add(typeof(Product).GetProperty("Price"), "price");
mgr.Add(typeof(Product).GetProperty("InStock"), "inStock");
mgr.Add(typeof(Product).GetProperty("Timestamp"), "timestamp");
mgr.Add(typeof(Product).GetProperty("Weight"), "weight");


Second. Establishment of the library

After mapping the class, you must initialize the library to operate the SOLR instance. Usually run at the start of a program:

Startup.init<product> ("HTTP://LOCALHOST:8983/SOLR");

Then you need the service locator for the Solrnet service instance to operate:




var solr = servicelocator.current.getinstance<isolroperations<product>> ();
Solr. Delete (Solrquery.all)
. ADD (p)
. Commit ();
var products = Solr. Query (New solrquerybyrange<decimal> ("Price", 10m, 100m));




Third, inquiry

Support for different query methods:

1. Simple Query

Whatever you give it are passed straight to SOLR ' s q parameter

Isolroperations<product> SOLR = ...

var products1 = Solr. Query (New Solrquery ("Lucene")); Search for ' Lucene ' in the default field

var products2 = Solr. Query (New Solrquery ("NAME:SOLR")); Search for "SOLR" in the "Name" field


2. Query by Field

This allows your to define field name and value separately:

Isolroperations<product> SOLR = ...

var products = Solr. Query (New Solrquerybyfield ("name", "SOLR")); Search for "SOLR" in the "Name" field


It also has the benefit that it handles special character to you.

3. Query by Range

Creates a range query:

Isolroperations<product> SOLR = ...

var products = Solr. Query (New solrquerybyrange<decimal> ("Price", 100m, 250.50m)); Search for price between and 250.50


4. Query by list of values

var q = new Solrqueryinlist ("name", "SOLR", "Samsung", "Maxtor");

Is the same as "NAME:SOLR or Name:samsung or name:maxtor"


5. "Any value" query

It ' s often convenient to-what documents have a field defined or not:

var q = new Solrhasvaluequery ("name");


is equivalent to the SOLR query ' name:[* to *] '

6. Query Operators

can use the && and | | Operators to concatenate operators with the expected results:

var q = new Solrquery ("SOLR") && new Solrquery ("Name:desc");

Generates the query "SOLR and Name:desc"

The plus (+) operator is also overloaded.

var q = new Solrquery ("SOLR") + new Solrquery ("Name:desc");


Creates the query "Solr name:desc"

To negate a query, can call not () on it or just use the '! ' operator:

var q =!new solrquery ("SOLR");


Creates the query "-SOLR"



Fourth, Facets inquiry

Solrnet supports faceted searching.

There are basically three kinds of facet queries:

1. Querying by Field

2. Date Facets

3. Arbitrary facet queries

Facet queries are issued through the Facetqueries property of Queryoptions. Then The Queryoptions instance is passed to the server instance.






1. Querying by Field

Querying by the handled by the Solrfacetfieldquery class. Results are available through the Facetfields property.

Example:print all categories sorted by popularity.




isolroperations<document> SOLR =
... var r = Solr. Query (Solrquery.all, new queryoptions {
Rows = 0,
Facet = new Facetparameters {
Queries = new[ ] {new Solrfacetfieldquery ("category")}
}
);
foreach (var facet in r.facetfields["category"]) {
Console.WriteLine ("{0}: {1}", facet.) Key, facet. Value);
}




2. Date Facets

Date facet queries create facets from date ranges. Sample Code:




ISolrOperations<Product> solr = ...
ISolrQueryResults<Product> results = solr.Query(SolrQuery.All, new QueryOptions {
    Facet = new FacetParameters {
        Queries = new[] {
            new SolrFacetDateQuery("timestamp", new DateTime(2001, 1, 1).AddDays(-1) /* range start */, new DateTime(2001, 1, 1).AddMonths(1) /* range end */, "+1DAY" /* gap */) {
                HardEnd = true,
                Other = new[] {FacetDateOther.After, FacetDateOther.Before}
            },
        }
    }
});
DateFacetingResult dateFacetResult = results.FacetDates["timestamp"];
foreach (KeyValuePair<DateTime, int> dr in dateFacetResult.DateResults) {
    Console.WriteLine(dr.Key);
    Console.WriteLine(dr.Value);
}



3.     arbitrary facet queries

arbitrary facet queries are handled By the Solrfacetquery class. Results are available through the Facetqueries property.

Example:segregate items by price (less than $500-more than $)






ISolrOperations<Product> solr = ...
ISolrQueryResults<Product> results = solr.Query(SolrQuery.All, new QueryOptions {
    Facet = new FacetParameters {
        Queries = new[] {
            new SolrFacetDateQuery("timestamp", new DateTime(2001, 1, 1).AddDays(-1) /* range start */, new DateTime(2001, 1, 1).AddMonths(1) /* range end */, "+1DAY" /* gap */) {
                HardEnd = true,
                Other = new[] {FacetDateOther.After, FacetDateOther.Before}
            },
        }
    }
});
DateFacetingResult dateFacetResult = results.FacetDates["timestamp"];
foreach (KeyValuePair<DateTime, int> dr in dateFacetResult.DateResults) {
    Console.WriteLine(dr.Key);
    Console.WriteLine(dr.Value);
}




For a overview of faceted search with SOLR, Solrfacetingoverview.


Fifth, highlight

Sample Code:




var results = Solr.        Query (New Solrquerybyfield ("Features", "noise"), new Queryoptions {
highlight = new Highlightingparameters {
Fields = new[] {"Features"},
}
});
foreach (Var h in results). Highlights[results[0]] {
Console.WriteLine ("{0}: {1}", H.key, H.value);
}



 
would print for example:

Features: <em>noise</em>guard, Silentseek Technology, Fluid Dynamic Bearing (FDB) Motor

SOLR Reference documentation:http://wiki.apache.org/solr/ Highlightingparameters


Sixth, more like this

This option returns a list of similar Documents for each document returned in the results of the original query.

Parameters are defined through the Morelikethis property to the Queryoptions

example:searching for Apache , for each document in the result search for similar documents in the "Cat" (category) and "Manu" (manufacturer) fields:< br>






ISolrBasicOperations<Product> solr = ...
var results = solr.Query(new SolrQuery("apache"), new QueryOptions {
    MoreLikeThis = new MoreLikeThisParameters(new[] {"cat", "manu"}) {
        MinDocFreq = 1, // minimum document frequency
        MinTermFreq = 1, // minimum term frequency
    },
});
foreach (var r in results.SimilarResults) {
    Console.WriteLine("Similar documents to {0}", r.Key.Id);
    foreach (var similar in r.Value)
        Console.WriteLine(similar.Id);
    Console.WriteLine();
}



All parameters defined in the SOLR docs are supported.


Seventh, spell check

You'll need to install of the spellcheckcomponent in the standard request for handler in order for this.

Next, a spellcheck dictionary must be provided. Normally a default dictionary is created by invoking Buildspellcheckdictionary () once per index:

Isolroperations<product> SOLR = ...

Solr. Buildspellcheckdictionary ();


Now I can start issuing spellchecking queries by defining the SpellCheck parameter in the queryoptions:




isolroperations<product> SOLR =
... var results = Solr. Query ("IPO appl", new Queryoptions {
spellcheck = new Spellcheckingparameters {Collate = true}
});




Then you to the suggestions from results. spellchecking, i.e.:




foreach (Var sc in results.) spellchecking) {
Console.WriteLine ("Query: {0}", SC.)    Query);
foreach (Var s in SC.)                    Suggestions) {
Console.WriteLine ("Suggestion: {0}", s);
}
}




Which would print something like:

Query:ipo

Suggestion:ipod

Query:appl

Suggestion:apple


All of the spellcheckcomponent parameters are supported, except for the extendedresults option.


Eighth, Stats

This feature provides your with simple statistics for numeric fields within the query results:

Sample usage:




ISolrOperations<Product> solr = ...
var results = solr.Query(SolrQuery.All, new QueryOptions {
    Rows = 0,
    Stats = new StatsParameters {
        Facets = new[] { "inStock" },
        FieldsWithFacets = new Dictionary<string, ICollection<string>> {
            {"popularity", new List<string> {"price"}}
        }
    }
});
 
foreach (var kv in results.Stats) {
    Console.WriteLine("Field {0}: ", kv.Key);
    Console.WriteLine("Min: {0}", s.Min);
    Console.WriteLine("Max: {0}", s.Max);
    Console.WriteLine("Sum of squares: {0}", s.SumOfSquares);
    foreach (var f in s.FacetResults) {
        Console.WriteLine("Facet: {0}", f.Key);
        foreach (var fv in f.Value) {
            Console.WriteLine("Facet value: {0}", fv.Key);
            Console.WriteLine("Min: {0}", fv.Value.Min);
            Console.WriteLine("Max: {0}", fv.Value.Max);
            Console.WriteLine("Sum of squares: {0}", fv.Value.SumOfSquares);
        }
    }
}




Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.