Elastcisearch.Nest 7.x series `` pseudo-official translation: quick to try Elasticsearch by NEST

  • This series has been completed, the full version can be seen : https://blog.zhuliang.ltd/categories/Elasticsearch/
  • This blog series is "fake" official document translation (more localized), is not completely official document translation, but in inspection, testing the original document and converted to their own insights "accurate" translation. There are different opinions / Description of ill place, please forgive, generous Paizhuan :)
  • Seeing the official document: https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/introduction.html
  • This series of corresponding version environment: ElasticSearch @ 7.3.1, NEST @ 7.3.1, IDE and development platforms default to VS2019, .NET CORE 2.1

Elasticsearch.Net and NEST comparative illustration:

  • Elasticsearch official offers two official client libraries for .NET: Elasticsearch.Net and NEST.
  • It can be simply understood as Elasticsearch.Net is a subset of NEST.
  • NEST internal use ElasticSearch.Net, and the client can begin to expose ElasticSearch.Net by NEST.
  • But NEST contains some advanced features ElasticSearch.Net do not have, such as:
    • Strongly typed query DSL: the object type all requests and responses may be converted 1: .NET type 1.
    • CLR automatically converted to the data type.

Basically .NET project to the point where you want to use on ElasticSearch, you can directly select NEST.

When used as a client NEST recommended to use as a single object ElasticClient embodiment.

  • ElasticClient is designed to be thread-safe.
  • ES The cache is divided according to ConnectionSettings, that service is a side cache for each ConnectionStrings
  • Exception: When you need to connect different ES cluster, do not use a singleton, and should use a different ConnectionStrings different ElasticClient.

Quick

  • When using the Nest Nest version of the agreement must be consistent with ElasticSearch version, ES server version 7.3.1, you must use version 7.3.1 Nest
  • The following examples are implanted (singleton) through IoC, you can also be achieved by directly singleton pattern.

Configuration, connection ElasticSearch

Configuration class:

public class ElasticSearchSettings
{
    public string ServerUri { get; set; }
    public string DefaultIndex { get; set; } = "defaultindex";
}

ElasticSearch client:

  • Connected to ElasticSearch, and set a default index
public class ElasticSearchClient : IElasticSearchRepository
{
    private readonly ElasticSearchSettings _esSettings;
    private readonly ElasticClient _client;

    public ElasticSearchClient(IOptions<ElasticSearchSettings> esSettings)
    {
        _esSettings = esSettings.Value;

        var settings = new ConnectionSettings(new Uri(_esSettings.ServerUri)).DefaultIndex(_esSettings.DefaultIndex);
        _client = new ElasticClient(settings);
    }

    public ElasticSearchClient(ElasticSearchSettings esSettings)
    {
        _esSettings = esSettings;
        var settings = new ConnectionSettings(new Uri(_esSettings.ServerUri)).DefaultIndex(_esSettings.DefaultIndex);
        _client = new ElasticClient(settings);
    }
}

The connection configuration using the password credentials

ElasticSearch can specify password on Uri directly, as follows:

    var uri = new Uri("http://username:password@localhost:9200")
    var settings = new ConnectionConfiguration(uri);

Use connection pooling

ConnectionSettings not only supports connection of single address, also provides different types of connection pool to let you configure the client, such as the use SniffingConnectionPool to connect three Elasticsearch nodes in the cluster, the client will use this type of connection pool to maintain the cluster the list of available nodes, and will send a circular manner invocation request.

var uris = new[]{
    new Uri("http://localhost:9200"),
    new Uri("http://localhost:9201"),
    new Uri("http://localhost:9202"),};

var connectionPool = new SniffingConnectionPool(uris);var settings = new ConnectionSettings(connectionPool)
    .DefaultIndex("people");

_client = new ElasticClient(settings);

NEST tutorial series 2-1 connection: Configuration options | Configuration Options

Index (Indexing)

  • Here the "index" to be understood as a verb, to understand better with indexing, would represent a document is inserted into the ES.

Suppose the following classes User.cs

public class User
{
    public Guid Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Index (Indexing) / add a document to the ES

//同步
var response = _client.IndexDocument<User>(new User
            {
                Id = new Guid("3a351ea1-bfc3-43df-ae12-9c89e22af144"),
                FirstName = "f1",
                LastName = "l1"
            });

//异步
var response = _client.IndexDocumentAsync<User>(new User
            {
                Id = new Guid("82f323e3-b5ec-486b-ac88-1bc5e47ec643"),
                FirstName = "f2",
                LastName = "l2"
            });
  • The current method is substantially contain (at the end of the asynchronous method * Async) synchronous and asynchronous versions
  • The method determines whether IndexDocument add document already exists (according to _id), if present, add fails.
  • NEST will automatically Id attribute as the ES _id, more on the way id inference Seeing Bowen: NEST tutorial series 9-3 Conversion: Id inference

The final request to the following address:

PUT  /users/_doc/3a351ea1-bfc3-43df-ae12-9c89e22af144

Inquire

Lambda expressions to query by category

By Search Ways to make queries.

var result = _client.Search<User>(s=>s.From(0)
                .Size(10)
                .Query(q=>q.Match(m=>m.Field(f=>f.LastName).Query("l1"))));

Request the following URL:

POST /users/_search?typed_keys=true
  • The search is based on more than "users" search index

How to search across all indexes on the ES? By AllIndices (), as follows:

var result = _client.Search<User>(s=>s
    .AllIndices()  //指定在所有索引上进行查询
    .From(0)
    .Size(10)
    .Query(q=>q.Match(m=>m.Field(f=>f.LastName).Query("l1"))));

Consider the following documents:

//users 索引
"hits" : [
      {
        "_index" : "users",
        "_type" : "_doc",
        "_id" : "3a351ea1-bfc3-43df-ae12-9c89e22af144",
        "_score" : 1.0,
        "_source" : {
          "id" : "3a351ea1-bfc3-43df-ae12-9c89e22af144",
          "firstName" : "f1",
          "lastName" : "l1"
        }
      },
      {
        "_index" : "users",
        "_type" : "_doc",
        "_id" : "05245504-053c-431a-984f-23e16d8fbbc9",
        "_score" : 1.0,
        "_source" : {
          "id" : "05245504-053c-431a-984f-23e16d8fbbc9",
          "firstName" : "f2",
          "lastName" : "l2"
        }
      }
    ]
// thirdusers 索引
"hits" : [
  {
    "_index" : "thirdusers",
    "_type" : "_doc",
    "_id" : "619ad5f8-c918-46ef-82a8-82a724ca5443",
    "_score" : 1.0,
    "_source" : {
      "firstName" : "f1",
      "lastName" : "l1"
    }
  }
]

Users can get to the final and thirdusers _id index were acquired as 3a351ea1-bfc3-43df-ae12-9c89e22af144 and document information 619ad5f8-c918-46ef-82a8-82a724ca5443 of.

You can query data from all types (types) and all indexes (index) by .AllTypes () and .AllIndices (), generated in the last query / _search request. About Type and Index, respectively reference: NEST tutorial series 9-6 Conversion: Document Paths document path and jump: NEST tutorial series 9-7 Conversion: Indices Paths index path

Query by the query object

Query by SearchRequest object.

Example: Query LastName = "l1" in the index of all document information

var request = new SearchRequest(Nest.Indices.All) //在所有索引上查询
{
    From = 0,
    Size = 10,
    Query = new MatchQuery
    {
        Field = Infer.Field<User>(f => f.LastName),
        Query = "l1"
    }
};
var response = _client.Search<User>(request);

Generated request URL is:

POST  /_all/_search?typed_keys=true

Elasticsearch.Net used to query attributes by .LowLever

Elasticsearch.Net opportunity to use the query:

  • When there is bug, that is, using the NEST's Search and SearchRequest unusual client, consider query with Elasticsearch.Net provided.
  • When you want to use an anonymous object or JSON string to query the time.
var response = _client.LowLevel.Search<SearchResponse<User>>("users", PostData.Serializable(new
{
    from = 0,
    size = 10,
    query = new
    {
        match = new
        {
            lastName = "l1"
        }
    }
}));

Aggregate query

In addition to the structured and unstructured queries, ES also supports polymerization (Aggregations) Query:

var result = _client.Search<User>(s => s
    .Size(0) //设置为 0 ,可以让结果只包含聚合的部分:即 hits 属性中没有结果,聚合结果显示在 ”aggregations“
    .Query(q =>
        q.Match(m =>
            m.Field(f => f.FirstName)
                .Query("f2")))
    .Aggregations(a => //使用 terms 聚合,并指定到桶 last_name 中
        a.Terms("last_name", ta =>
            ta.Field(f => f.LastName)))
    );
  • Polymerization generally used term to get the number of documents in each bucket, each bucket will lastName as keywords.

More Actions on aggregated visible this: NEST Tutorial Series 8 Polymerization: Writing aggregations | Polymerization

Guess you like

Origin www.cnblogs.com/deepthought/p/12231714.html