利用NEST2.0 在C#中操做Elasticsearch

前言:本文主要演示瞭如何經過c#來操做elasticsearch,分兩個方面來演示:

索引數據

搜索數據

Note: 注意我索引數據和搜索數據是兩個不一樣的例子,沒有先後依賴關係php

準備工做:須要在visual studio 用NuGet 搜索 NEST,下載NEST 2.3便可java

注意elasticsearch和 NEST的版本,版本差別可能會致使寫法不一樣node

1、 索引數據演示

下面的c#代碼有以下要點:python

1. 經過es服務器 localhost:9200來定義es client

2. 導入前經過定義字段類型的類,自動mapping

var mappingBlogPost = elastic.Map(s => s.AutoMap());

Resume 這個類要提早根據數據類型進行定義:c++

using System;
namespace BotEsNest
{
    using Nest;
    [ElasticsearchType(Name = "candidate", IdProperty = "Id")]
    public class Resume
    {
        [String(Name = "id", Index = FieldIndexOption.NotAnalyzed)]
        public Guid? Id { get; set; }
 
        [String(Name = "name", Index = FieldIndexOption.Analyzed)]
        public string Name { get; set; }
 
        [String(Name = "age", Index = FieldIndexOption.NotAnalyzed)]
        public long Age { get; set; }
 
        [String(Name = "skills", Index = FieldIndexOption.Analyzed)]
        public string Skills { get; set; }
    }
}

3. 構造數據

4. 導入數據

using Nest;
using System;
using System.Linq;
 
namespace BotEsNest
{
    public class ImportEs
    {
        public static string  ElasticsearchMethod()
        {
            var node = new Uri("http://localhost:9200");
            var indexName = "esbot";
            var settings = new ConnectionSettings(node).DefaultIndex(indexName);
            var elastic = new ElasticClient(settings);
            var res = elastic.ClusterHealth(); //
            Console.WriteLine(res.Status);
            if (!elastic.IndexExists(indexName).Exists)
            {
                var createIndexResponse = elastic.CreateIndex(indexName);
                var mappingBlogPost = elastic.Map<Resume>(s => s.AutoMap());
                //Console.WriteLine("createIndexResponse=" + createIndexResponse.IsValid);
                //Console.WriteLine("mappingBlogPost=" + mappingBlogPost.IsValid);
            }
            string[] nameArray = { "Cody", "Blake", "Dennis", "Evan ", "Harris", "Jason ", "Lambert ", "Louis ", "Milton ", "Cody" };
            string[] skillArray = { "c#", "c++", "java", "python", "php", "Linux", "ruby", "matlab", "perl", "powershell" };
            long[] ageRange = { 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 };
 
            for (int i = 0; i < 10; i++)
            {
                var resume = new Resume
                {
                    Id = Guid.NewGuid(),
                    Name = nameArray[i],
                    Age = ageRange[i],
                    Skills = "My skill is Azure and " + skillArray[i]
                };
                IIndexResponse bulkIndexReponse = elastic.Index(resume, p => p
                   .Type(typeof(Resume))
                   .Id(i)
                   .Refresh());
            }
            var searchResult = elastic.Search<Resume>(sr => sr.Query(q => q.MatchAll()));
            //Console.WriteLine(searchResult.Hits.Count());
            //Console.ReadLine();
            var resumesCount = searchResult.Hits.Count().ToString();
            return resumesCount;
        }
    }
}

搜索返回的信息都包含在searchResult中。索引esbot也已經建立。能夠經過Kibana或者REST API進行查看shell

2、搜索數據演示

1. 此處的數據源是es官網的bank account,我已經提早手動導入

2. 搜索數據的關鍵在於用lambda表達式構造搜索內容,下段代碼是爲了動態定製參數所作

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
 
namespace BotEsNest.Ext
{
    public class Extension
    {
        public static Dictionary<string, Expression<Func<Resume, object>>> ResumeDIctionary()
        {
            return new Dictionary<string, Expression<Func<Resume, object>>>
            {
                { "age",p=>p.Age},
                { "name",p=>p.Name}
            };
        }
        public static Dictionary<string, Expression<Func<Bank, object>>> BankDictionary()
        {
            return new Dictionary<string, Expression<Func<Bank, object>>>
            {
                { "account_number",p=>p.account_number},
                { "age",p=>p.age},
                {"balance",p=>p.balance},
            };
        }
    }
}

3.定義搜索類型

using Nest;
 
namespace BotEsNest
{
    [ElasticsearchType(Name = "account", IdProperty = "Id")]
    public class Bank
    {
        public long account_number { get; set; }
        public string address { get; set; }
        public long age { get; set; }
        public long balance { get; set; }
        public string city { get; set; }
        public string email { get; set; }
        public string employer { get; set; }
        public string firstname { get; set; }
        public string gender { get; set; }
        public string lastname { get; set; }
        public string state { get; set; }
    }
}

4. 搜索,我大概寫了三種搜索方式,好比:返回存款在40000到40100的人,返回數據中帶有Miltoon的人,返回數據中帶有35的人,返回結構存在searchResponse中

using System;
using Nest;
using BotEsNest.Ext;
 
namespace BotEsNest
{
    public class Elasticsearch
    {
        public static string indexName = "bank";
        public static Uri node = new Uri("http://localhost:9200");
        public static ConnectionSettings settings = new ConnectionSettings(node).DefaultIndex(indexName);
        public static ElasticClient elastic = new ElasticClient(settings);
        public static ISearchResponse<Bank> esSearchNumber()
        {
            string dictionaryKey = "balance";
            var dictionary = Extension.BankDictionary();
            var rangeField = dictionary[dictionaryKey];
            var gt = 40000;
            var lt = 40100;
            var searchResponse = elastic.Search<Bank>(es => es
                                                             .Query(q => q
                                                                   .Range(r => r
                                                                       .Name("")
                                                                       .Field(rangeField)
                                                                           .GreaterThan(gt)
                                                                           .LessThan(lt)
                                                                           .Boost(2.0))));
            return searchResponse;
        }
        public static ISearchResponse<Bank>esSearchString()
        {
            string quertStr = "Miltoon";
            var searchResponse = elastic.Search<Bank>(es => es
                                                             .Query(q =>
                                                               q.QueryString(qs => qs.Query(quertStr))));
            return searchResponse;
        }
        public static ISearchResponse<Bank>esSearchField()
        {
            string queryStr = "35";
            string dictionaryKey = "age";
            var dictionary = Extension.BankDictionary();
            var rangeField = dictionary[dictionaryKey];
            var searchResponse = elastic.Search<Bank>(es => es
                                            .Query(q => q
                                                    .Match(m => m
                                                        .Field(rangeField)
                                                            .Query(queryStr))));
            return searchResponse;
        }
    }
}
相關文章
相關標籤/搜索