在.Net环境下使用elasticsearch实现大数据量的搜索

最近因为项目需要使用搜索引擎,因此尝试使用.Net去操作elasticsearch,把使用过程记录如下:

1.安装elasticsearch

2.安装elasticsearch插件

3.使用NEST操作elasticsearch

elasticsearch下文使用简称ES,ES已经更新到了6.*,经常使用的应该是2.*和5.*,其中5.*当然对2.*更新了许多功能,但是在初学者最直观的改变是关联插件的版本,2.*关联插件的版本号基本上是乱的,需要去插件对应的网站上查询,但是5.*对应的插件版本基本上和ES本身的版本号一致,这就避免了为找相应插件而做的很多无谓的工作。

1.安装elasticsearch

安装之前请先安装Jdk,我使用的是1.8版本,安装完后配置环境变量,安装过程略过。

我这里使用的是5.6.0版本。下载路径如下 https://www.elastic.co/downloads/past-releases/elasticsearch-5-6-0

下载完成后,将下载文件直接解压到安装目录下即可。

安装完成后,就是启动ES在bin目录下可以运行elasticsearch.bat在命令行界面启动(命令行不能关闭),也可以运行elasticsearch-service.bat启动ES的服务进程,这样就不用每次开机启动了。

配置文件在config/elasticsearch.yml中,每次修改完配置需要服务重启,切记切记。

启动成功后,打开浏览器,输入默认的url和端口  

http://localhost:9200/   

如果启动成功,则会出现如下页面,说明安装成功了

2.安装elasticsearch插件

ES有许多插件用来帮助我们使用,其中我觉得最主要的有两个插件

 1)esheader    可以使用在web页面上访问esheader的集群数据

 2)  analysis-ik   中文的分词插件,默认的分词功能在搜索时只能将中文分成一个一个的单字

esheader的安装

esheader在2.*版本上是可以直接在命令行中进行安装的,但是5.*版本上不能这样做了,网上采用的办法很麻烦,我找到一种比较简单的办法。

其实说到底esheader就是在web页面上向es服务器发送http请求,并获取结果进行展示,其实esheader实质上就是一个java web网站,因此只需要将它部署到tomcat服务器上,运行即可。

ip和端口号,需要和安装ES配置的相一致,而且需要将ES的配置文件修改为允许跨域访问即在config/elasticsearch.yml最后追加如下配置,然后重启服务

http.cors.enabled: true
http.cors.allow-origin: "*"

然后访问tomcat上对应的网页即可,如下图。说明esheader安装成功了!!

analysis-ik 的安装

ik可以直接在命令行下面安装(前提是知道ik文件的url)

在ES的bin目录下打开控制台运行 ,即可

.\elasticsearch-plugin install https://github.com/medcl/elasticsearch-analysis-ik/releases/download/v5.6.0/elasticsearch-analysis-ik-5.6.0.zip

 安装完成后ES的plugins目录中会添加对应插件的目录

3.使用NEST访问ES

新建一个.net控制台项目,打开NuGet管理器,搜索NEST,然后安装,如图。我安装的是5.6.0版本,不知道其余版本是否OK,感兴趣的朋友可以试试

 

安装完成后,就可以编写代码了

        private static void AddData()
        {
            //1.通過es服務器 localhost:9200 來定義es client
            var node = new Uri("http://localhost:9200");
            var indexName = "products";
            var settings = new ConnectionSettings(node).DefaultIndex(indexName);
            var elastic = new ElasticClient(settings);

            //es服務器健康檢查
            var res = elastic.ClusterHealth();
            Console.WriteLine(res.Status);

            //2.創建索引esbot
            //if (!elastic.IndexExists(indexName).Exists)
            //{
            //    var createIndexResponse = elastic.CreateIndex(indexName);
            //    var mappingBlogPost = elastic.Map<Account>(s => s.AutoMap());
            //}
            //var mappingBlogPost = elastic.Map<Account>(s => s.AutoMap());
            //List<Account> accounts = new List<Account>() { new Account { Id = 2, Name = "aaa", Password = "bbb" }, new Account { Id = 3, Name = "ccc", Password = "ddd" } };
            List<Product> duodians = new TestEntities().duodian.ToList().Select(a => a.ToProduct()).ToList();


            elastic.IndexMany(duodians, indexName);

        }

        private static void SimpleSelect()
        {
            //1.通過es服務器 localhost:9200 來定義es client
            var node = new Uri("http://localhost:9200");
            var indexName = "products";
            var settings = new ConnectionSettings(node).DefaultIndex(indexName);
            var elastic = new ElasticClient(settings);

            //5. 簡單搜索
            //var searchResult = elastic.Search<Product>(sr => sr.Query(q => q.MatchAll()).From(0).Size(100));
            //var searchResult = elastic.Search<Product>(sr => sr.Query(q => q.QueryString(qs=>qs.Query("苏泊尔"))));
            var searchResult = elastic.Search<Product>(sr => sr.Query(q => q.Match(qm => qm.Field(f => f.title).Query("给你省小号擀面杖"))));

            return;
        }
View Code
    [ElasticsearchType(Name = "Product", IdProperty = "GuidId")]
    public class Product
    {
        [Keyword(Name = "GuidId", Index = true)]
        public string GuidId { get; set; } = Guid.NewGuid().ToString();

        [Number(NumberType.Long, Name = "Id")]
        public int id { get; set; }

        [Text(Name = "Title", Index = true, Analyzer = "ik_max_word")]
        public string title { get; set; }

        [Keyword(Name = "Img", Index = false)]
        public string img { get; set; }

        [Keyword(Name = "Lunfanimg", Index = false)]
        public string lunfanimg { get; set; }

        [Keyword(Name = "Spec", Index = false)]
        public string spec { get; set; }

        [Keyword(Name = "Xcimg", Index = false)]
        public string xcimg { get; set; }

        [Keyword(Name = "Skuid", Index = false)]
        public string skuid { get; set; }

        [Keyword(Name = "Pimg", Index = false)]
        public string pimg { get; set; }

        [Keyword(Name = "Plunfanimg", Index = false)]
        public string plunfanimg { get; set; }

        [Keyword(Name = "Pxcimg", Index = false)]
        public string pxcimg { get; set; }

        [Keyword(Name = "Categoryid", Index = false)]
        public string categoryid { get; set; }

        [Keyword(Name = "Price", Index = false)]
        public string price { get; set; }

        [Keyword(Name = "Brandname", Index = false)]
        public string brandname { get; set; }

        [Keyword(Name = "Categoryname", Index = false)]
        public string categoryname { get; set; }

        [Keyword(Name = "Created", Index = false)]
        public System.DateTime created { get; set; }
    }

    public static class duodianExtension
    {
        public static Product ToProduct(this duodian duodian)
        {
            return new Product
            {
                brandname = duodian.brandname,
                categoryid = duodian.categoryid,
                id = duodian.id,
                img = duodian.img,
                lunfanimg = duodian.lunfanimg,
                pimg = duodian.pimg,
                plunfanimg = duodian.plunfanimg,
                price = duodian.price,
                pxcimg = duodian.pxcimg,
                skuid = duodian.skuid,
                spec = duodian.spec,
                title = duodian.title,
                xcimg = duodian.xcimg,
                created = duodian.created,
                categoryname = duodian.categoryname
            };
        }
    }
View Code

猜你喜欢

转载自www.cnblogs.com/gamov/p/10373936.html