Elasticsearch.net search Getting Started Guide Chinese (translation)

Source: Internet
Author: User
Tags automap connection pooling createindex failover

elasticsearch.net Search Getting started using the Chinese version, Elasticsearch. NET is a very low-level and flexible client that doesn't care how you build your own requests and responses. It's very abstract, so all elasticsearchapi are represented as methods, notElasticsearch.net search Getting Started User Guide Chinese version

Why do elasticsearch.net have two clients?

Elasticsearch.net is a very low-level and flexible client that doesn't care how you build your own requests and responses. It's very abstract, so all Elasticsearch APIs are represented as methods, not much about how you want to build Json/request/response objects, and it has built-in configurable, overridable failover mechanisms for the cluster.

Elasticsearch.net has a lot of flexibility and if you want to improve your search service better, you can use it to do it for your clients.

Nest is a high-level client that can map all request and response objects, have a strongly typed query DSL (domain-specific language), and can use. NET features such as covariant, Auto Mapping of Pocos, Nest is still used internally by the Elasticsearch.net client.

NEST Client

Elasticsearch.net (NEST) client provides a strong type query DSL, convenient for users to use, source code download.

First, how to install nest

Open the Tools menu for VS, and through the NuGet Package Manager console, enter the following command to install Nest

Install-package NEST

The following three DLLs are referenced after installation

Elasticsearch. Net.DLL (2. 4. 4) Nest.DLL (2. 4. 4)Newtonsoft. Json. dll (version 9.0)           
Second, link Elasticsearch

You can use connection pooling to link to a elasticsearch cluster through a single node or by specifying multiple nodes, using a connection pool that is more advantageous than a single node linking to Elasticsearch, such as support for load balancing, failover, and so on.

Via a single-point link:

New Uri ("http://myserver:9200");  New ConnectionSettings (node); new Elasticclient (settings);  

Through connection pooling Links:

New uri[]{    new Uri ("http://myserver1:9200"), new Uri (    new URI("http://myserver3:9200")} ; new Staticconnectionpool (nodes); new connectionsettings (pool); new Elasticclient (settings);       
NEST Index

In order to know which index the request needs to manipulate, the Elasticsearch API expects to receive one or more index names as part of the request.

One, the specified index

1. You can specify the default index by using ConnectionSettings. Defaultindex (). When a specific index is not specified in a request, Nest will request a default index.

New ConnectionSettings ()    . Defaultindex ("Defaultindex");

2. ConnectionSettings can be used with. Mapdefaulttypeindices () to specify an index that is mapped to a CLR type.

New ConnectionSettings ()    . Mapdefaulttypeindices (m = M        . ADD ("projects")); 

Note: Pass. Mapdefaulttypeindices () specifies that the index should take precedence over the pass. Defaultindex () specifies the index and is more suitable for simple objects (POCO)

3. You can also display the specified index name for the request, for example:

var response = client. Index (student, S=>s.index ("db_test"));  var result = client. Search<student> (s = S.index ("db_test"));  var result = client. Delete<student> (null, S = = S.index ("db_test"));      

Note: This priority is the highest when the actual specified index name for the request is higher than the index specified in both of these ways.

4. Some Elasticsearch APIs (such as query) can use one or more index names or send requests using the _all special flag, requesting multiple or all nodes on the nest

Request a single nodevar singlestring = Nest.Indices.Index ("Db_studnet");var singletyped = nest.indices.index<student> (); Isearchrequest singlestringrequest =New Searchdescriptor<student> (). Index (singlestring); Isearchrequest singletypedrequest =New Searchdescriptor<student> (). Index (singletyped);Request multiple nodesvar manystrings = Nest.Indices.Index ("db_studnet", "db_other_student");  var manytypes = nest.indices.index<student> (). And<otherstudent> (); Isearchrequest manystringrequest = new Searchdescriptor<student> (). Index (manystrings); Isearchrequest manytypedrequest = new Searchdescriptor<student> (). Index (manytypes); //Request all nodes var indicesall = Nest.Indices.All;  var allindices = nest.indices.allindices;isearchrequest indicesallrequest = new Searchdescriptor<student> () . Index (Indicesall); Isearchrequest allindicesrequest = new Searchdescriptor<student> (). Index (allindices);          
Second, create an index

The Elasticsearch API allows you to create indexes while configuring the index, for example:

New Createindexdescriptor ("db_student")    . Settings (s = s.numberofshards (5). Numberofreplicas (1)); client. CreateIndex (descriptor);   

This specifies that the number of shards for this index is 5 and the number of replicas is 1.

Third, delete the index

The Elasticsearch API allows you to delete an index, for example:

New Deleteindexdescriptor ("Db_student"). Index ("db_student"); client. Deleteindex (descriptor) 

Here is the index name "db_student" to be deleted, and the following are more delete use cases:

Removes all indexes  new Deleteindexdescriptor ("Db_student") under the node that contains the specified index. Allindices (); 
NEST Mapping

Nest provides a variety of mapping methods, described here under attribute custom mapping.

First, simple implementation

1. Define the Poco required by the business and specify the required attribute

[Elasticsearchtype (Name ="Student")]PublicClassstudent{[nest.string (Index = fieldindexoption.notanalyzed)]public string Id {get; set; } [nest.string (Analyzer = public string Name {get; set;} [Nest.string (Analyzer = public string Description {get; set;} public datetime datetime {get; set;} // lazy man Build station   http://www.51xuediannao.com/         

2, then we pass. Automap () to implement the mapping

New Createindexdescriptor ("db_student")    . Settings (s = s.numberofshards (5). Numberofreplicas (1)). Mappings (ms = Ms. Map<student> (m = M.automap ())); client. CreateIndex (descriptor);     

Note: Pass. Properties () can override mappings defined through attribute

Ii. Introduction of attribute

1, Stringattribute

Property name value type Description
Analyzer String Parser name, value contains standard, simple, whitespace, stop, keyward, pattern, language, snowball, custom, etc., see the parser for more information, click Elasticsearch Analyzers
Boost Double Weighted value, the higher the value the greater the score
Nullvalue String Default value when inserting a document, if the data is null
Index Fieldindexoption Whether to use the parser, use fieldindexoption.analyzed by default, disable the use of the parser fieldindexoption.notanalyzed

2, Numberattribute

Property name value type Description
Type Numbertype constructor parameter, specifying the type of the current property, Numbertype.default, Float, Double, Integer, Long, short, Byte
Boost Double Weighted value, the higher the value the greater the score
Nullvalue Double Default value when inserting a document, if the data is null

3, Booleanattribute

Property name value type Description
Boost Double Weighted value, the higher the value the greater the score
Nullvalue Double Default value when inserting a document, if the data is null

4, Dateattribute

Property name value type Description
Boost Double Weighted value, the higher the value the greater the score
Nullvalue String Default value when inserting a document, if the data is null
Format String

5, Objectattribute

Property name value type Description
Type String/type constructor parameter, specifying the type of the current property T
Dynamic Dynamicmapping
NEST Search

Nest provides support for lambda chain query DLS (domain-specific language), following a simple implementation and a brief description of each query.

First, simple implementation

1, define searchdescriptor, facilitate the implementation of complex business in the project

New Nest.searchdescriptor<models.esobject> (); var result = client. Search<student> (x = query) 

2. Retrieve the title and content containing key, and the author is not equal to "Pretty Woman" document

Query. Query (Q = Q.bool (b = B.must (m = m.multimatch (t = T.fields (f + f.field (obj = obj). Title). Field (obj = obj. Content)). Query (key)). Mustnot (m = m.querystring (t = T.fields (f + f.field (obj = = obj). Author)). Query ("Pretty Woman")))); //c# Tutorial http://www.51xuediannao.com/c_asp_net/          

Attention:

If Elasticsearch uses the default participle, the title and content attribute are [nest.string (Analyzer = "standard")]

If Elasticsearch is using IK participle, the title and content attribute are [nest.string (analyzer = "Ikmaxword")] or [nest.string (analyzer = "ik _smart ")]

Author's attribute is [nest.string (Index = fieldindexoption.notanalyzed)] and disables the use of analyzers

3, filter author equal to "History Creek" document

Query. Postfilter (x = x.term (t = = T.field (obj = obj). Author). Value ("History Creek"    ));

4, filter the author equals "History Creek" or equal to "friendship boat" document, matching multiple authors between spaces separated by space

Query. Postfilter (x = x.querystring (t = T.fields (f + f.field (obj = = obj). Author)). Query ("The Boat of the Historical Creek Friendship")));    

5. Filter the number of documents between 1~100

Query. Postfilter (x = x.range (t = = T.field (obj = obj). Number). Greaterthanorequals (1). Lessthanorequals ());    

6, sort, according to the score flashback arrangement

Query. Sort (x = X.field ("_score", Nest.SortOrder.Descending)); 

7. Define highlighting Styles and fields

Query. Highlight (h = h    . Pretags ("<b>")    . Posttags ("</b>")    . Fields (        f = F.field (obj = obj). Title), F = F.field (obj = obj. Content), F = F.field ("_all"       ));

8, assemble the contents of the query, organize the data, convenient to call the previous paragraph

var list = result. Hits.select (c =new Models.esobject () {Id = c.source.id, Title = c.highlights = null? C.source.title:c.highlights.keys.contains ( "Title")? string. Join (" title "]. Highlights): C.source.title, //highlighted content, a record that appeared several times contents = C.highlights = null? C.source.content:c.highlights.keys.contains ( "Content")? string. Join (//highlighted content, a record that appeared several times Author = C.source.author, number = c.source.number, Isdisplay = c.source.isdisplay, Tags = c.source.tags, Comments = C.Source.Comme NTS, DateTime = C.source.datetime,})            
Second, query DSL introduction

To be sorted out ...

Elasticsearch.net Document

Document actions include adding/updating documents, updating documents locally, deleting documents, and corresponding bulk operations documentation methods.

I. Add/update documents and bulk operations

Add/update a single document

Client. Index (student); 

Bulk Add/Update documents

New list<student> (); client. Indexmany<student> (list);
Second, the partial Update single document and batch operation

Update a single document locally

Object> ("002", UpT = UpT. Doc ("Jiangshan Beauty"}); 

Update Bulk documents locally

New list<"002"};  New list<ibulkoperation> ()}; foreach ("Hu Dao"}; bulkQuest.Operations.Add (operation);} var result = client. Bulk (bulkquest);    
Iii. deleting documents and bulk operations

Delete a single document

Client. Delete<student> ("001");

Delete a document in bulk

New list<"002"};  New list<ibulkoperation> ()}; foreach (inIDs) {bulkQuest.Operations.Add (new bulkdeleteoperation<student> (v));} var result = client. Bulk (bulkquest); Original: http://edu.dmeiyang.com/book/nestusing.html      

Elasticsearch.net Search Getting started using the Chinese version (translation)

Related Article

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.