elasticsearch在C#中的使用

版权声明:本文为马立弘原创文章,欢迎引用,谢绝转载。 https://blog.csdn.net/manimanihome/article/details/55682494

elsticsearch中安装了x-pack后,查询时就需要用户名和密码了。
无账号密码,不可访问
curl http://192.168.0.2:9200/testindex/_count?pretty=true
Authentication Required

访问basic认证的页面
(1)通过user选项带上账号密码,返回正常数据
curl –user elastic:changeme http://192.168.0.2:9200/testindex/_count?pretty=true

(2)在url中添加用户名和密码来访问:
http://elastic:[email protected]:9200/testindex/_count?pretty=true

(3)在请求头中添加Authorization来访问:
Authorization: “Basic 用户名和密码的base64加密字符串”

//HTTP Basic 验证客户端 C#实现:
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);

request.Method = "GET";
request.ContentType = "application/x-www-form-urlencoded";
request.Credentials = CredentialCache.DefaultCredentials;

//获得用户名密码的Base64编码
string code= Convert.ToBase64String(Encoding.ASCII.GetBytes(string.Format("{0}:{1}", "username", "password")));

//添加Authorization到HTTP头
request.Headers.Add("Authorization", "Basic " + code);

HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());

string content= reader.ReadToEnd();

常用C#查询组件

官方组件Elasticsearch.Net & NEST

NEST手册


--
//建立映射类
    [ElasticsearchType(Name = "user", IdProperty = "Ncid")]
    public class User
    {

        [Number(Name = "ncid")]
        public int Ncid { get; set; }


        [Text(Name = "name")]
        public string Name { get; set; }


        [Text(Name = "webclass")]
        public string Webclass { get; set; }


        [Date(Name = "birthday", Format = "yyyy-MM-dd", IgnoreMalformed = true, Coerce = true)]
        public DateTime? Birthday { get; set; }



        [Text(Name = "eduname")]
        public string Eduname { get; set; }


        [Number(Name = "sex", IgnoreMalformed = true, Coerce = true)]
        public int Sex { get; set; }



        [Text(Name = "selfment")]
        public string Selfment { get; set; }



        [Date(Name = "refreshtime", IgnoreMalformed = true, Coerce = true)]
        public DateTime? Refreshtime { get; set; }


    }


//链接:
        private ElasticClient Client()
        {
            var nodes = new Uri[]
            {
                new Uri("http://192.168.0.2:9200")
            };
            var pool = new StaticConnectionPool(nodes);
            var settings = new ConnectionSettings(pool)
                .DefaultIndex("testindex")
                .BasicAuthentication("elastic", "changeme");

            return new ElasticClient(settings);

        }

//添加记录
            var client = Client();


            var modUser4 = new User
            {
                Ncid = 4,
                Name = "mygod4",
                Sex = 1,
                Eduname = "硕士",
                Birthday = DateTime.Now.AddYears(-20),
                Selfment = "中国长春市长春药店",
                Webclass = "www.b.com",
                Refreshtime = DateTime.Now,
            };

            client.Create(modUser4); 


//删除记录
            var client = Client();


            //删除单条记录
            var rtnDel = client.Delete<User>(new DocumentPath<User>(2));


            //删除多条记录
            var delIds = new List<int>() { 4, 5 };
            var bulkDel = new BulkRequest() { Operations = new List<IBulkOperation>() };
            foreach (var id in delIds)
            {
                bulkDel.Operations.Add(new BulkDeleteOperation<User>(id));
            }
            var resultDel = client.Bulk(bulkDel);

//更新记录
            var client = Client();
    //更新单条记录
            IUpdateRequest<User, User> request = new UpdateRequest<User, User>(new DocumentPath<User>(2))
            {
                Doc = new User()
                {
                    Name = "胡三刀",
                    Selfment = "test4update........"

                }
            };
            var resp = client.Update<User, User>(request);



            //更新多条记录
            var insIds = new List<int>() { 4, 5 };
            var bulkUpdate = new BulkRequest() { Operations = new List<IBulkOperation>() };
            foreach (var id in insIds)
            {
                var operation = new BulkUpdateOperation<User, object>(id);
                operation.Doc = new User{ Name = "胡一刀" };
                bulkUpdate.Operations.Add(operation);
            }
            var result = client.Bulk(bulkUpdate);

//查询
            //查询一条数据
            var modUser = client.Get<User>(3); 
            var tweet = JsonConvert.SerializeObject(modUser.Source);

        //查询多条数据
            var modList = client.Search<User>( s => s
            .From(0)
            .Size(10)
            .Query(q =>
                    q.Term(t => t.Webclass, "www.b.com")
                    || q.Match(mq => mq.Field(f => f.Selfment).Query("中国"))
                )
            );

NEST使用方法
http://www.cnblogs.com/huhangfei/p/5726650.html

其他组件
plainElastic.net

参考:

http://www.cnblogs.com/eggTwo/p/4425269.html

http://blog.csdn.net/wulex/article/details/52138564

http://www.cnblogs.com/hyl8218/archive/2011/07/04/2097394.html
http://blog.csdn.net/kingson88/article/details/51252606

猜你喜欢

转载自blog.csdn.net/manimanihome/article/details/55682494