plainelastic.net elasticsearch实现搜索业务

本文介绍使用plainelastic elasticsearch先介绍api使用方法,然后给出一个实现搜索业务的一个plainelastic.net实例教程 1、PlainElastic.Net下载 1)源码下载:https://github.com/Yegoroff/PlainElastic.Net 2)通

本文介绍使用plainelastic elasticsearch先介绍api使用方法,然后给出一个实现搜索业务的一个plainelastic.net实例教程

 1、PlainElastic.Net下载

  1)源码下载:https://github.com/Yegoroff/PlainElastic.Net

  2)通过NuGet Packages下载

  使用plainelastic elasticsearch实现搜索业务

  备注:通过这种方式下载,有可能因为PlainElastic.Net引用的Newtonsoft.Json.dll版本与原有项目中的不一致到报错,因此建议下载源码,将源码中的Newtonsoft.Json.dll版本更换为当前项目的版本

 2、封装PlainElastic.Net帮助类

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using PlainElastic.Net;
using PlainElastic.Net.Queries;
using PlainElastic.Net.Serialization;

namespace Amy.Toolkit.PlainElastic
{
    public class ElasticSearchHelper
    {
        public static readonly ElasticSearchHelper Intance = new ElasticSearchHelper();

        private ElasticConnection Client;

        private ElasticSearchHelper()
        {
            Client = new ElasticConnection("localhost", 9200);
        }

        /// <summary>
        /// 数据索引
        /// </summary>       
        /// <param name="indexName">索引名称</param>
        /// <param name="indexType">索引类型</param>
        /// <param name="id">索引文档id,不能重复,如果重复则覆盖原先的</param>
        /// <param name="jsonDocument">要索引的文档,json格式</param>
        /// <returns>索引结果</returns>
        public IndexResult Index(string indexName, string indexType, string id, string jsonDocument)
        {

            var serializer = new JsonNetSerializer();

            string cmd = new IndexCommand(indexName, indexType, id);

            OperationResult result = Client.Put(cmd, jsonDocument);

            var indexResult = serializer.ToIndexResult(result.Result);

            return indexResult;
        }

        /// <summary>
        /// 数据索引
        /// </summary>       
        /// <param name="indexName">索引名称</param>
        /// <param name="indexType">索引类型</param>
        /// <param name="id">索引文档id,不能重复,如果重复则覆盖原先的</param>
        /// <param name="jsonDocument">要索引的文档,object格式</param>
        /// <returns>索引结果</returns>
        public IndexResult Index(string indexName, string indexType, string id, object document)
        {
            var serializer = new JsonNetSerializer();

            var jsonDocument = serializer.Serialize(document);

            return Index(indexName, indexType, id, jsonDocument);
        }

        /// <summary>
        /// 全文检索
        /// </summary>
        /// <typeparam name="T">搜索类型</typeparam>
        /// <param name="indexName">索引名称</param>
        /// <param name="indexType">索引类型</param>
        /// <param name="query">查询条件(单个字段或者多字段或关系)</param>
        /// <param name="from">当前页(0为第一页)</param>
        /// <param name="size">页大小</param>
        /// <returns>搜索结果</returns>
        public SearchResult<T> Search<T>(string indexName, string indexType, QueryBuilder<T> query, int from, int size)
        {
            var queryString = query.From(from).Size(size).Build();
            
            var cmd = new SearchCommand(indexName, indexType);

            var result = Client.Post(cmd, queryString);

            var serializer = new JsonNetSerializer();

            return serializer.ToSearchResult<T>(result);
        }
    }
} 

 3、在control中的实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PlainElastic.Net;
using PlainElastic.Net.Queries;
using Amy.WebUI.Controllers;


namespace Amy.WebUI.Areas.Admin.Controllers
{
    public class SearchController : BasicController
    {
        /// <summary>
        /// 创建索引/更新索引
        /// </summary>
        public ActionResult AddIndexByPlainElastic(Models.SearchObject model)
        {
            if (string.IsNullOrEmpty(model.Id))
            {
                model.Id = IDHelper.Id32;
            }

            model.DateTime = DateTime.Now;

            var result = Amy.Toolkit.PlainElastic.ElasticSearchHelper.Intance.Index("db_test", "searchobject", model.Id, model);

            return JRCommonHandleResult(!string.IsNullOrEmpty(result._id));
        }

        /// <summary>
        /// 搜索数据
        /// </summary>
        public ActionResult SearchByPlainElastic(string key, int page = 0)
        {
            #region 定义查询内容
            var query = new QueryBuilder<Models.SearchObject>()
                //查询,多字段匹配(Title和Content匹配key中的任意一个单词)
                .Query(x =>
                    x.QueryString(t => t.Fields(obj => obj.Title, obj => obj.Content).Query(key))
                )
                //过滤,数据为启用状态并且大小在40~150之间
                .Filter(x => 
                    x.And(w=>
                        w.Term(t => t
                            .Field(obj => obj.IsEnable).Value("true")
                        )
                        .Range(t => t
                            .Field(obj => obj.Size).From("40").To("150")
                        )
                    )
                )
                //排序,按照时间倒序排列
                .Sort(x => x.Field("DateTime", SortDirection.desc))
                //高亮,定义高亮样式及字段
                .Highlight(h => h
                    .PreTags("<b>")
                    .PostTags("</b>")
                    .Fields(
                        f => f.FieldName("Title").Order(HighlightOrder.score),
                        f => f.FieldName("Content").Order(HighlightOrder.score),
                        f => f.FieldName("_all")
                    )
                );
            #endregion

            var result = Amy.Toolkit.PlainElastic.ElasticSearchHelper.Intance.Search<Models.SearchObject>("db_test", "searchobject", query, page, 10);

            #region 拼装查询内容
            var list = result.hits.hits.Select(c => new Models.SearchObject()
            {
                Id = c._source.Id,
                Title = c.highlight == null ? c._source.Title : c.highlight.Keys.Contains("Title") ? string.Join("", c.highlight["Title"]) : c._source.Title, //高亮显示的内容,一条记录中出现了几次
                Content = c.highlight == null ? c._source.Content : c.highlight.Keys.Contains("Content") ? string.Join("", c.highlight["Content"]) : c._source.Content, //高亮显示的内容,一条记录中出现了几次
                Size = c._source.Size,
                IsEnable = c._source.IsEnable,
                DateTime = c._source.DateTime,
            }).ToPageList(page + 1, 10, result.hits.total);
            #endregion

            return JRSuccess(list.ToJsonByJsonNet());
        }

    }
}  

 4、代码中使用到的伪搜索对象

namespace Amy.WebUI.Areas.Admin.Models
{
    public class SearchObject
    {
        public string Id { get; set; }

        public string Title { get; set; }

        public string Content { get; set; }

        public int Size { get; set; }

        public bool IsEnable { get; set; }

        public DateTime DateTime { get; set; }
    }
} 

 5、UI测试页面效果

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值