基於netcore對ElasitSearch客戶端NEST查詢功能的簡單封裝NEST.Repository

来源:https://www.cnblogs.com/snaildev/archive/2018/03/28/8665445.html
-Advertisement-
Play Games

NEST.Repository A simple encapsulation with NEST client for search data form elasticsearch. github API NESTReaderRepository TEntity Get(TKey id); TEnt ...


NEST.Repository

A simple encapsulation with NEST client for search data form elasticsearch.

github

API

NESTReaderRepository

TEntity Get(TKey id);
TEntity Get(Func<QueryContainerDescriptor<TEntity>, QueryContainer> filterExp = null,
            Func<SourceFilterDescriptor<TEntity>, ISourceFilter> includeFieldExp = null,
            Expression<Func<TEntity, object>> sortExp = null, SortOrder sortType = SortOrder.Ascending);
Tuple<long, List<TEntity>> GetList(Func<QueryContainerDescriptor<TEntity>, QueryContainer> filterExp = null,
            Func<SourceFilterDescriptor<TEntity>, ISourceFilter> includeFieldExp = null,
            Expression<Func<TEntity, object>> sortExp = null, SortOrder sortType = SortOrder.Ascending
           , int limit = 10, int skip = 0)

NESTReaderRepositoryAsync

Task<TEntity> GetAsync(TKey id);
Task<TEntity> GetAsync(Func<QueryContainerDescriptor<TEntity>, QueryContainer> filterExp = null,
            Func<SourceFilterDescriptor<TEntity>, ISourceFilter> includeFieldExp = null,
            Expression<Func<TEntity, object>> sortExp = null, SortOrder sortType = SortOrder.Ascending);
Task<Tuple<long, List<TEntity>>> GetListAsync(Func<QueryContainerDescriptor<TEntity>, QueryContainer> filterExp = null,
            Func<SourceFilterDescriptor<TEntity>, ISourceFilter> includeFieldExp = null,
            Expression<Func<TEntity, object>> sortExp = null, SortOrder sortType = SortOrder.Ascending
           , int limit = 0, int skip = 0)

Depend on

NEST 6.0.2
Repository.IEntity 2.0.1 (or you can write IEntity<T> interface and you entity inherit it.)

How to Use

First, you need have an entity inherit IEntity<T>, T is type of PrimaryKey. eg

[Serializable]
[BsonIgnoreExtraElements]
public class User : IEntity<long>
{
    [BsonId]
    public long ID { get; set; }

    public double Age { get; set; }

    public double Sex { get; set; }

    public string Like { get; set; }
}

Second, you need have a repository inherit NESTReaderRepository or NESTReaderRepositoryAsync. eg

public class UserRepo : NESTReaderRepository<User, long>
{
    public static string connString = "http://localhost:9200/";

    public UserRepo()
        : base(connString)
    {

    }
}

Now, you can search data with simple api. eg

 static void Main(string[] args)
 {
    Repository.Container.RepositoryContainer.Register<UserRepo>();
    var userRepo = Repository.Container.RepositoryContainer.Resolve<UserRepo>();

    var user = userRepo.Get(9);
    var users = userRepo.GetList(
        filterExp: q => +q.Range(r => r.Field(f => f.Age).GreaterThan(13).LessThan(28)), 
        includeFieldExp: p => p.Includes(i => i.Fields(f => f.Age, f => f.Sex, f => f.Like)),
        sortExp: s => s.Age,
        sortType: Nest.SortOrder.Ascending,
        limit: 100,
        skip: 0
    );
 }

How to write a Query

0x00. Structured Search

By default, documents will be returned in _score descending order, where the _score for each hit is the relevancy score calculated for how well the document matched the query criteria.

q => q.DateRange(r => r
    .Field(f => f.{Field with DateTime Type})
    .GreaterThanOrEquals(new DateTime(2017, 01, 01))
    .LessThan(new DateTime(2018, 01, 01))
)

The benefit of executing a query in a filter context is that Elasticsearch is able to forgo calculating a relevancy score, as well as cache filters for faster subsequent performance.

 q => q.Bool(b => b.Filter(bf => bf
    .DateRange(r => r
        .Field(f => f.{Field with DateTime Type})
        .GreaterThanOrEquals(new DateTime(2017, 01, 01))
        .LessThan(new DateTime(2018, 01, 01))
        )
    )
)

0x01. Unstructured Search

Full text queries (find all documents that contain "Russ" in the lead developer first name field)

q => q.Match(m => m
    .Field(f => f.LeadDeveloper.FirstName)
    .Query("Russ")
)

0x02. Combining Search

q => q.Bool(b => b
    .Must(mu => mu
        .Match(m => m
            .Field(f => f.LeadDeveloper.FirstName)
            .Query("Russ")
        ), mu => mu
        .Match(m => m
            .Field(f => f.LeadDeveloper.LastName)
            .Query("Cam")
        )
    )
    .Filter(fi => fi
        .DateRange(r => r
            .Field(f => f.StartedOn)
            .GreaterThanOrEquals(new DateTime(2017, 01, 01))
            .LessThan(new DateTime(2018, 01, 01))
        )
    )
)

use operator

q => q.Match(m => m
        .Field(f => f.LeadDeveloper.FirstName)
        .Query("Russ")
    ) && q
    .Match(m => m
        .Field(f => f.LeadDeveloper.LastName)
        .Query("Cam")
    ) && +q
    .DateRange(r => r
        .Field(f => f.StartedOn)
        .GreaterThanOrEquals(new DateTime(2017, 01, 01))
        .LessThan(new DateTime(2018, 01, 01))
    )
)

Should ==> OR ==> ||
Must ==> And ==> &&
Must_Not ==> NOT==> !
Filter ==> +

the query will be converted to a bool query if use any operator, and the answer to the bool query is always yes or no , so that will not score.

Reference

https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/writing-queries.html

https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/bool-queries.html


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • OOP的好處,關鍵的OOP概念,構造函數和析構函數,靜態類成員,instanceof關鍵字,輔助函數,自動載入函數 ...
  • 原文發佈在特克斯博客www.susmote.com 之前給大家講了關於python的背景知識,還有Python的優點和缺點,相信通過之前的介紹很多人已經清楚自己到底要不要選擇學習Python,如果已經很有興趣了,那麼你就可以自己查看一些有關Python的官方文檔,或是買本書啃啃,如果你暫時還沒什麼興 ...
  • .NET Core是一個開源通用的開發框架,具有跨平臺能力,我們在享受其性能飆升的同時,也面臨了一些問題。通過觀察 NetCore 程式的線上運行情況發現 ,負載高的情況下應用程式占用記憶體較大,本文將針對這個問題展開討論,對比分析不同GC工作模式下的.NetCore性能與記憶體管理的表現。通過查找資料 ...
  • 看圖: 這裡可以看到是二層嵌套!!使用C#如何實現?? 思路:使用list集合實現 → 建立類 → list集合 → 微軟的 Newtonsoft.Json (一款.NET中開源的Json序列化和反序列化) sonXMText類 using System; using System.Collecti ...
  • IEnumerator和IEnumerable 從名字常來看,IEnumerator是枚舉器的意思,IEnumerable是可枚舉的意思。 瞭解了兩個介面代表的含義後,接著看源碼: IEnumerator: IEnumerable: 發現IEnumerable只有一個GetEnumerator函數, ...
  • 因為今天是最後一天了,我趕緊在這次結束前提出一些前一晚上想到的問題 1. 在TDD的循環中有重構,那 DB 也會進行重構嗎? 在TDD 的重構的過程,其實也經常會重構資料庫 , 但重構資料庫這裡有一個很重要的點,是要如何做 DB Migration from : Odd-e CSD Course 經 ...
  • 這篇文章主要來講講c#中的泛型,因為泛型在c#中有很重要的位置,對於寫出高可讀性,高性能的代碼有著關鍵的作用。 一、什麼是泛型? 泛型是 2.0 版 C# 語言和公共語言運行庫 (CLR) 中的一個非常重要的新功能。 我們在編程程式時,經常會遇到功能非常相似的模塊,只是它們處理的數據不一樣。但我們沒 ...
  • 本文總結了在 C# 當中,介面與抽象類的一些異同,來與大家共用。 一、抽象類 (1) 抽象方法只作聲明,而不包含實現,可以看成是沒有實現體的虛方法 (2) 抽象類不能被實例化 (3) 抽象類可以但不是必須有抽象屬性和抽象方法,但是一旦有了抽象方法,就一定要把這個類聲明為抽象類 (4) 具體派生類必須 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...