栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

.net core Elasticsearch.Net基本操作

.net core Elasticsearch.Net基本操作

1.加入依赖

Elasticsearch.model
Elasticsearch.Net

2.实体类

namespace Elasticsearch.model
{
    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }
}

3.编写工具类

using Elasticsearch.model;
using Elasticsearch.Net;
using Nest;

namespace Elasticsearch.config
{
    public class ElasticsearchHelper
    {
        private static ElasticClient? _client = null;

        public static ElasticClient GetClient() {

            if (_client == null) {
                var nodes = new Uri[]
            {
                new Uri("http://xxx:9200")
            };

                var pool = new StaticConnectionPool(nodes);
                var settings = new ConnectionSettings(pool);
                _client = new ElasticClient(settings);
            }
            
            return _client;
        }

        public static object Search() {

            var response = GetClient().Search(s => s
                .Index("myuserindex") 
                .From(0)
                .Size(10)
                .Query(q => 
                    q.Term(t => t.Name, "kimchy") 
                    || q.Match(mq => mq.Field(f => f.Name).Query("tom"))
                )
            );

            return response.documents.ToList();
        }

        public static object Insert() {

            var user = new User
            {
                Id = 2,
                Name = "tom",
                Age = 12
            };

            var response = GetClient().Index(user, idx => idx.Index("myuserindex"));
            return response;
        }
    }
}

4.测试

using Elasticsearch.config;
using Microsoft.AspNetCore.Mvc;

namespace Elasticsearch.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MyController : Controllerbase
    {
        [HttpGet(Name = "my")]
        public object Get()
        {
            ElasticsearchHelper.Insert();
            return ElasticsearchHelper.Search();
        }
    }
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/673566.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号