安装.NetSDK : Install-Package PlainElastic.Net
操作类:ElasticSearchHelper
using PlainElastic.Net;
using PlainElastic.Net.Queries;
using PlainElastic.Net.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DotNetMVC.Common.Elasticsearch
{
public class ElasticSearchHelper
{
public static readonly string INDEXNAME = "ImageLibrarySystem";
public static readonly string INDEXTYPE = "Images";
public static readonly ElasticSearchHelper Intance = new ElasticSearchHelper();
private ElasticConnection Client;
private ElasticSearchHelper()
{
Client = new ElasticConnection("127.0.0.1", 9200);
}
/// <summary>
/// 创建索引
/// </summary>
/// <param name="id"></param>
/// <param name="jsonDocument"></param>
/// <returns></returns>
public IndexResult Index(string id, string jsonDocument)
{
return Index(INDEXNAME, INDEXTYPE, id, jsonDocument);
}
/// <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="id"></param>
/// <param name="document"></param>
/// <returns></returns>
public IndexResult Index(string id, object document)
{
return Index(INDEXNAME, INDEXTYPE, id, document);
}
/// <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"></param>
/// <param name="size"></param>
/// <returns></returns>
public SearchResult<T> Search<T>(QueryBuilder<T> query, int from, int size)
{
return Search<T>(INDEXNAME, INDEXTYPE, query, from, size);
}
/// <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);
}
/// <summary>
/// 删除索引
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public IndexResult Delete(string id)
{
return Delete(INDEXNAME, INDEXTYPE, id);
}
/// <summary>
/// 删除索引
/// </summary>
/// <param name="indexName"></param>
/// <param name="indexType"></param>
/// <param name="id"></param>
/// <returns></returns>
public IndexResult Delete(string indexName, string indexType, string id)
{
var serializer = new JsonNetSerializer();
string cmd = new IndexCommand(indexName, indexType, id);
OperationResult result = Client.Delete(cmd);
var indexResult = serializer.ToIndexResult(result.Result);
return indexResult;
}
}
}
ImageDTO img = imageService.GetDTOById(id);
//创建搜索索引
ElasticSearchHelper.Intance.Index(id.ToString(), new
{
Id = img.Id,
CategoryNumber = img.CategoryName,
ImgName = img.ImgName,
Name = img.Name,
Source = img.Source,
Keyword = img.Keyword,
SmallImgUrl = img.SmallImgUrl,
BigImgUrl = img.BigImgUrl,
WorkFileName = img.WorkFileName,
WorkFileUrl = img.WorkFileUrl,
CategoryName = img.CategoryName,
CategoryPath = img.CategoryPath
});
var query = new QueryBuilder<ImageDTO>().Query(b => b.Bool(m => m.Must(t => t.Term(t1 => t1.Field("Id").Value(id.ToString())))));
var searchResult = ElasticSearchHelper.Intance.Search<ImageDTO>( query, 0, 1000);
//检查搜索索引是否存在
if (searchResult.hits.total > 0)
{
//return Json(new AjaxResult { Status = "error", ErrorMsg = "删除记录数:"+ searchResult.hits.total });
//删除索引
ElasticSearchHelper.Intance.Delete(id.ToString());
}
Must : 必须
Should : 或者
/// <summary>
/// 获取查询数据
/// </summary>
/// <param name="id">categpryId</param>
/// <param name="keyword"></param>
/// <returns></returns>
[HttpPost]
public ActionResult GetDataES(long id, string keyword)
{
DataTablesModel model = new DataTablesModel();
if (id <= 1 && string.IsNullOrEmpty(keyword))
{
model.draw = 1;
model.recordsFiltered = 0;
model.recordsTotal = 0;
model.data = new { };
return Json(model);
}
var query = new QueryBuilder<ImageDTO>()
.Query(b =>
b.Bool(m =>
//并且关系
m.Must(t => t.QueryString(t1 => t1.DefaultField("CategoryPath").Query("|" + id + "|")))
.Must(t =>
//分词的最小单位或关系查询
t.QueryString(t1 => t1.Fields(img => img.CategoryName, img => img.ImgGroup,img => img.ImgName, img => img.Name, img => img.Source, img => img.Keyword).Query(keyword))
)
)
)
//排序
//.Sort(c => c.Field("Id", SortDirection.asc))
//添加高亮
.Highlight(h => h
.PreTags("<span class='colorRed'>")
.PostTags("</span>")
.Fields(
//f => f.FieldName(n => n.ImgName).Order(HighlightOrder.score),
f => f.FieldName(n => n.Name).Order(HighlightOrder.score),
f => f.FieldName(n => n.Source).Order(HighlightOrder.score),
f => f.FieldName(n => n.Keyword).Order(HighlightOrder.score),
f => f.FieldName("_all")
)
);
var searchResult = ElasticSearchHelper.Intance.Search<ImageDTO>(query, 0, 1000);
// ImageDTO[] images = imageService.GetData(keyword, id);
model.draw = 1;
model.recordsFiltered = searchResult.hits.total;
model.recordsTotal = searchResult.hits.total;
model.data = searchResult.hits.hits.Select(c => new
{
Id = c._source.Id,
ImgName = c.highlight == null || !c.highlight.Keys.Contains("ImgName") ? c._source.ImgName : string.Join("", c.highlight["ImgName"]), //高亮显示的内容,一条记录中出现了几次
Name = c.highlight == null || !c.highlight.Keys.Contains("Name") ? c._source.Name : string.Join("", c.highlight["Name"]), //高亮显示的内容,一条记录中出现了几次
Source = c.highlight == null || !c.highlight.Keys.Contains("Source") ? c._source.Source : string.Join("", c.highlight["Source"]), //高亮显示的内容,一条记录中出现了几次
Keyword = c.highlight == null || !c.highlight.Keys.Contains("Keyword") ? c._source.Keyword : string.Join("", c.highlight["Keyword"]), //高亮显示的内容,一条记录中出现了几次
SmallImgUrl = c._source.SmallImgUrl,
BigImgUrl = c._source.BigImgUrl,
WorkFileName = c._source.WorkFileName,
WorkFileUrl = c._source.WorkFileUrl
});
return Json(model);
}
参考资料:
http://www.cnblogs.com/eggTwo/p/4425269.html