Elasticsearch簡單學習

1、依賴的導入

<!--ES依賴-->
<dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId>
</dependency>

2、客戶端鏈接

RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(HttpHost.create("http://localhost:9200")));

3、索引庫的相關操作

1、索引庫的創建
@Test
void createTestIndex() throws IOException {/*創建索引庫*///1.創建Request對象,索引庫名稱必須為小寫字母CreateIndexRequest request = new CreateIndexRequest("test_index");String source = "{\n" +"        \"mappings\":{\n" +"        \"properties\":{\n" +"            \"id\":{\n" +"                \"type\":\"integer\"\n" +"            },\n" +"            \"name\":{\n" +"                \"type\":\"text\",\n" +"                \"analyzer\":\"ik_max_word\"\n" +"            },\n" +"            \"age\":{\n" +"                \"type\":\"integer\"\n" +"            },\n" +"            \"sex\":{\n" +"                \"type\":\"keyword\"\n" +"            },\n" +"            \"bossId\":{\n" +"                \"type\":\"integer\"\n" +"            },\n" +"            \"departmentId\":{\n" +"                \"type\":\"integer\"\n" +"            }\n" +"        }\n" +"    }\n" +"}";//2.準備請求的參數:DSL語句request.source(source, XContentType.JSON);//3.發請求client.indices().create(request, RequestOptions.DEFAULT);
}
2、判斷索引庫是否存在
@Test
void existsTestIndex() throws IOException {/*判斷索引庫是否存在*///1.創建Request對象,名稱必須為小寫字母GetIndexRequest request = new GetIndexRequest("test_index");//2.發請求boolean is = client.indices().exists(request, RequestOptions.DEFAULT);System.out.println(is);
}
3、刪除索引庫
@Test
void deleteTestIndex() throws IOException {/*刪除索引庫*///1.創建Request對象,名稱必須為小寫字母DeleteIndexRequest request = new DeleteIndexRequest("test_index");//2.發請求client.indices().delete(request, RequestOptions.DEFAULT);
}

4、文檔的操作

1、創建文檔
@Test
void createDocTest() throws IOException {//從數據庫中獲取數據對象Employee employee = employeeMapper.selectAllById(1);//1. 創建Request對象IndexRequest request = new IndexRequest("test_index").id(employee.getId().toString());//2.準備json文檔String source = JSON.toJSONString(employee);//2.1準備json文檔request.source(source, XContentType.JSON);//3.發請求client.index(request, RequestOptions.DEFAULT);
}
2、獲取指定的文檔
@Test
void getDocTest() throws IOException {//1.創建Request對象GetRequest request = new GetRequest("test_index","1");//2.發請求,得到結果GetResponse response = client.get(request, RequestOptions.DEFAULT);//3.解析結果String json = response.getSourceAsString();System.out.println(json);Employee employee = JSON.parseObject(json, Employee.class);System.out.println(employee);
}
3、更新文檔
@Test
void updateDocTest() throws IOException {//1.創建Request對象UpdateRequest request = new UpdateRequest("test_index","1");//2.準備DSL語句request.doc("age",18);//3.發請求client.update(request,RequestOptions.DEFAULT);
}
4、刪除文檔
@Test
void deleteDocTest() throws IOException {//1.創建Request對象DeleteRequest request = new DeleteRequest("test_index","1");//2.發請求client.delete(request,RequestOptions.DEFAULT);
}
5、批量操作(創建)
@Test
void batchCreateDocTest() throws IOException {//1.創建Request對象BulkRequest request = new BulkRequest();//2.準備DSL語句,批量增加文檔List<Employee> employees = employeeMapper.selectAll();for(Employee e : employees){request.add(new IndexRequest("test_index").id(e.getId().toString()).source(JSON.toJSONString(e),XContentType.JSON));}//3.發請求client.bulk(request,RequestOptions.DEFAULT);
}

5、搜索文檔

1、分詞查詢-查詢全部
@Test
void matchAllTest() throws IOException {  //分詞查詢//1.準備RequestSearchRequest request = new SearchRequest("test_index");//2.組織DSL參數request.source() // 查詢全部.query(QueryBuilders.matchAllQuery());//3.發送請求SearchResponse response = client.search(request,RequestOptions.DEFAULT);//4.解析結果SearchHits searchHits = response.getHits();//4.1獲取總條數long total = searchHits.getTotalHits().value;System.out.println("總共有:" + total + "條數據");//4.2獲取文檔數組SearchHit[] hits = searchHits.getHits();//4.3遍歷數組for(SearchHit h : hits){String json = h.getSourceAsString();Employee employee = JSON.parseObject(json, Employee.class);System.out.println(employee);}
}
2、分詞查詢-指定字段
@Test
void matchQueryTest() throws IOException { //分詞查詢//1.準備RequestSearchRequest request = new SearchRequest("test_index");//2.組織DSL參數request.source() //查詢指定字段的值,也可以指定多個字段 .multiMatchQuery().query(QueryBuilders.matchQuery("name","晨"));//3.發送請求SearchResponse response = client.search(request,RequestOptions.DEFAULT);//4.解析結果SearchHits searchHits = response.getHits();//4.1獲取總條數long total = searchHits.getTotalHits().value;System.out.println("總共有:" + total + "條數據");//4.2獲取文檔數組SearchHit[] hits = searchHits.getHits();//4.3遍歷數組for(SearchHit h : hits){String json = h.getSourceAsString();Employee employee = JSON.parseObject(json, Employee.class);System.out.println(employee);}
}
3、精確查詢
@Test
void termQueryTest() throws IOException {  //精確查詢//1.準備RequestSearchRequest request = new SearchRequest("test_index");//2.組織DSL參數request.source() //精確查詢只能查詢 非text(分詞字段),如果查詢分詞字段,則自動采用模糊分詞查詢.query(QueryBuilders.termQuery("age","33"));//3.發送請求SearchResponse response = client.search(request,RequestOptions.DEFAULT);//4.解析結果SearchHits searchHits = response.getHits();//4.1獲取總條數long total = searchHits.getTotalHits().value;System.out.println("總共有:" + total + "條數據");//4.2獲取文檔數組SearchHit[] hits = searchHits.getHits();//4.3遍歷數組for(SearchHit h : hits){String json = h.getSourceAsString();Employee employee = JSON.parseObject(json, Employee.class);System.out.println(employee);}
}
4、范圍查詢
@Test
void rangeQueryTest() throws IOException {  //范圍查詢//1.準備RequestSearchRequest request = new SearchRequest("test_index");//2.組織DSL參數request.source() //范圍查詢,gte:大于等于,lte:小于等于,gt:大于,lt:小于.query(QueryBuilders.rangeQuery("age").gte(30).lte(35));//3.發送請求SearchResponse response = client.search(request,RequestOptions.DEFAULT);//4.解析結果SearchHits searchHits = response.getHits();//4.1獲取總條數long total = searchHits.getTotalHits().value;System.out.println("總共有:" + total + "條數據");//4.2獲取文檔數組SearchHit[] hits = searchHits.getHits();//4.3遍歷數組for(SearchHit h : hits){String json = h.getSourceAsString();Employee employee = JSON.parseObject(json, Employee.class);System.out.println(employee);}
}
5、復合查詢
@Test
void boolQueryTest() throws IOException {  //復合查詢//1.準備RequestSearchRequest request = new SearchRequest("test_index");//2.1創建復合查詢對象BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();//2.2添加查詢條件boolQuery.must(QueryBuilders.matchQuery("name","雨"));boolQuery.filter(QueryBuilders.rangeQuery("age").gte(20).lte(35));//2.3組織DSL參數request.source().query(boolQuery);//3.發送請求SearchResponse response = client.search(request,RequestOptions.DEFAULT);//4.解析結果SearchHits searchHits = response.getHits();//4.1獲取總條數long total = searchHits.getTotalHits().value;System.out.println("總共有:" + total + "條數據");//4.2獲取文檔數組SearchHit[] hits = searchHits.getHits();//4.3遍歷數組for(SearchHit h : hits){String json = h.getSourceAsString();Employee employee = JSON.parseObject(json, Employee.class);System.out.println(employee);}
}
6、分頁排序查詢
@Test
void pageSortQueryTest() throws IOException {  //分頁、排序查詢// 頁碼,每頁大小int page = 3,size = 10;//1.準備RequestSearchRequest request = new SearchRequest("test_index");//2組織DSL參數request.source().from((page-1)*size) // 包含form,(page-1)*size,是前端傳過來的頁碼和每頁條數.size(size).sort("id", SortOrder.ASC).query(QueryBuilders.matchAllQuery());//3.發送請求SearchResponse response = client.search(request,RequestOptions.DEFAULT);//4.解析結果SearchHits searchHits = response.getHits();//4.1獲取總條數long total = searchHits.getTotalHits().value;System.out.println("總共有:" + total + "條數據");//4.2獲取文檔數組SearchHit[] hits = searchHits.getHits();//4.3遍歷數組for(SearchHit h : hits){String json = h.getSourceAsString();Employee employee = JSON.parseObject(json, Employee.class);System.out.println(employee);}
}
6、高亮查詢
@Test
void highLightQueryTest() throws IOException {  //高亮查詢//1.準備RequestSearchRequest request = new SearchRequest("test_index");//2組織DSL參數request.source().highlighter(new HighlightBuilder() //高亮顯示.field("name") //字段名.requireFieldMatch(false) // 是否與查詢字段匹配) // 用的默認標簽 <em></em>.query(QueryBuilders.matchQuery("name","晨"));//3.發送請求SearchResponse response = client.search(request,RequestOptions.DEFAULT);//4.解析結果SearchHits searchHits = response.getHits();//4.1獲取總條數long total = searchHits.getTotalHits().value;System.out.println("總共有:" + total + "條數據");//4.2獲取文檔數組SearchHit[] hits = searchHits.getHits();//4.3遍歷數組for(SearchHit h : hits){String json = h.getSourceAsString();Employee employee = JSON.parseObject(json, Employee.class);// 高亮顯示,因為每條數據都是帶有 晨 的,所以每條數據都有一個HighlightField用于替換HighlightField name = h.getHighlightFields().get("name");//替換employee.setName(name.getFragments()[0].toString());System.out.println(employee);}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/bicheng/72612.shtml
繁體地址,請注明出處:http://hk.pswp.cn/bicheng/72612.shtml
英文地址,請注明出處:http://en.pswp.cn/bicheng/72612.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

macOS Sequoia 15.3 M3 Pro芯片 iOS 開發環境配置記錄(最新)

進行如下工作之前首先確保終端已翻墻&#xff0c;在ClashX選擇“復制終端代理命令”&#xff0c;在終端進行粘附并執行。 安裝 homebrew Homebrew 是 Mac 平臺的一個包管理工具&#xff0c;提供了許多Mac下沒有的Linux工具等。 /bin/bash -c "$(curl -fsSL https://raw…

迷你世界腳本組隊接口:Team

組隊接口&#xff1a;Team 彼得兔 更新時間: 2023-04-26 10:19:04 具體函數名及描述如下: 序號 函數名 函數描述 1 getNumTeam(...) 當前隊伍數量 2 getTeamPlayerNum(...) 獲取指定隊伍玩家數量 3 getTeamPlayers(...) 獲取指定隊伍玩家 4 random…

使用 Deepseek + kimi 快速生成PPT

前言 最近看到好多文章和視頻都在說&#xff0c;使用 Deepseek 和 kimi 能快速生成精美的 ppt&#xff0c;畢竟那都是別人說的&#xff0c;只有自己嘗試一次才知道結果。 具體操作 第一步&#xff1a;訪問 deepseek 我們訪問 deepseek &#xff0c;把我們想要輸入的內容告訴…

初始提示詞(Prompting)

理解LLM架構 在自然語言處理領域&#xff0c;LLM&#xff08;Large Memory Language Model&#xff0c;大型記憶語言模型&#xff09;架構代表了最前沿的技術。它結合了存儲和檢索外部知識的能力以及大規模語言模型的強大實力。 LLM架構由外部記憶模塊、注意力機制和語…

【IDEA】IDEA常用的VM配置,優化配置讓開發過程更順暢

日常開發中&#xff0c;如果使用IDEA卡頓、卡死&#xff0c;一般是需要根據自己電腦的實際性能調整VM參數&#xff0c;才能有更好的開發體驗。 設置方法 選擇Help>Edit Custom VM Options&#xff0c;粘貼以下內容&#xff0c;重啟 IntelliJ IDEA使配置生效。 idea64.exe.…

【Python爬蟲】利用代理IP爬取跨境電商AI選品分析

引言 隨著DeepSeek的流行&#xff0c;越來越多的用戶開始嘗試將AI工具融入到日常工作當中&#xff0c;借助AI的強大功能提高工作效率。最近又掀起了一波企業出海的小高潮&#xff0c;那么如果是做跨境電商業務&#xff0c;怎么將AI融入工作流中呢&#xff1f;在做跨境電商的時候…

【Flink銀行反欺詐系統設計方案】1.短時間內多次大額交易場景的flink與cep的實現

【flink應用系列】1.Flink銀行反欺詐系統設計方案 1. 經典案例&#xff1a;短時間內多次大額交易1.1 場景描述1.2 風險判定邏輯 2. 使用Flink實現2.1 實現思路2.2 代碼實現2.3 使用Flink流處理 3. 使用Flink CEP實現3.1 實現思路3.2 代碼實現 4. 總結 1. 經典案例&#xff1a;短…

C語言——鏈表

大神文獻&#xff1a;https://blog.csdn.net/weixin_73588765/article/details/128356985 目錄 一、鏈表概念 1. 什么是鏈表&#xff1f; 1.1 鏈表的構成 2. 鏈表和數組的區別 數組的特點&#xff1a; 鏈表的特點&#xff1a; 二者對比&#xff1a; 二…

Spring框架自帶的定時任務:Spring Task詳解

文章目錄 一、基本使用1、配置&#xff1a;EnableScheduling2、觸發器&#xff1a;Scheduled 二、拓展1、修改默認的線程池2、springboot配置 三、源碼分析參考資料 一、基本使用 1、配置&#xff1a;EnableScheduling import org.springframework.context.annotation.Config…

數據庫事務、樂觀鎖及悲觀鎖

參考&#xff1a;node支付寶支付及同步、異步通知、主動查詢支付寶訂單狀態 以下容結合上述鏈接查看 1. 什么是數據庫事務&#xff1f; 1.1. 連續執行數據庫操作 在支付成功后&#xff0c;我們在自定義的paidSuccess里&#xff0c;依次更新了訂單狀態和用戶信息。也就說這里…

Android 創建一個全局通用的ViewModel

&#xff08;推薦&#xff09;使用ViewModelStore 代碼示例&#xff1a; class MyApplication : Application(), ViewModelStoreOwner {private val mViewModelStore ViewModelStore()override fun onCreate() {super.onCreate()}override val viewModelStore: ViewModelSto…

SCI期刊推薦 | 免版面費 | 計算機領域:信息系統、軟件工程、自動化和控制

在學術研究領域&#xff0c;選擇合適的SCI期刊對科研成果的傳播與認可至關重要。了解SCI期刊的研究領域和方向是基礎&#xff0c;確保投稿內容與期刊主題相符。同時&#xff0c;要關注期刊的影響因子和評估標準&#xff0c;選擇具有較高影響力和學術認可度的期刊。閱讀期刊的投…

解鎖Android RemoteViews:跨進程UI更新的奧秘

一、RemoteViews 簡介 在 Android 開發的廣闊領域中&#xff0c;RemoteViews 是一個獨特且重要的概念&#xff0c;它為開發者提供了一種在其他進程中顯示視圖結構的有效方式。從本質上講&#xff0c;RemoteViews 并非傳統意義上在當前應用進程內直接渲染和操作的 View&#xf…

常見webshell工具的流量特征

1、蟻劍 1.1、蟻劍webshell靜態特征 蟻劍中php使用assert、eval執行&#xff1b;asp只有eval執行&#xff1b;在jsp使用的是Java類加載&#xff08;ClassLoader&#xff09;&#xff0c;同時會帶有base64編碼解碼等字符特征。 1.2、蟻劍webshell動態特征 查看流量分析會發現…

爬蟲系列之【數據解析之bs4】《四》

目錄 前言 一、用法詳解 1.1 獲取標簽內容 1.2 獲取標簽屬性 1.3 獲取標簽包裹的文本內容 1.4 獲取標簽列表 1.5 css 選擇器&#xff1a;select 二、實戰案例 完整代碼 前言 HTML數據解析 1、正則 2、xpath&#xff08;居多&#xff09; 3、css 選擇器&#xff08;bs…

Java-實現PDF合同模板填寫內容并導出PDF文件

可用于公司用戶合同導出pdf文件 效果圖 一、導入所需要jar包 <!--生成PDF--><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.11</version></dependency><dependency&…

【人工智能】GPT-4 vs DeepSeek-R1:誰主導了2025年的AI技術競爭?

前言 2025年&#xff0c;人工智能技術將迎來更加激烈的競爭。隨著OpenAI的GPT-4和中國初創公司DeepSeek的DeepSeek-R1在全球范圍內嶄露頭角&#xff0c;AI技術的競爭格局開始發生變化。這篇文章將詳細對比這兩款AI模型&#xff0c;從技術背景、應用領域、性能、成本效益等多個方…

前端開發10大框架深度解析

摘要 在現代前端開發中&#xff0c;框架的選擇對項目的成功至關重要。本文旨在為開發者提供一份全面的前端框架指南&#xff0c;涵蓋 React、Vue.js、Angular、Svelte、Ember.js、Preact、Backbone.js、Next.js、Nuxt.js 和 Gatsby。我們將從 簡介、優缺點、適用場景 以及 實際…

【MySQL】索引(頁目錄、B+樹)

文章目錄 1. 引入索引2. MySQL與磁盤交互的基本單位3. 索引的理解3.1 頁目錄3.2 B樹 4. 聚簇索引、非聚簇索引5. 索引的操作5.1 索引的創建5.1.1 創建主鍵索引5.1.2 創建唯一索引5.1.3 普通索引的創建5.1.4 全文索引的創建 5.2 索引的查詢5.3 刪除索引 1. 引入索引 索引&#…

python-串口助手(OV7670圖傳)

代碼 主python文件 import serial import serial.tools.list_ports import time import tkinter as tk from tkinter import ttk import numpy as np from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg from matplotlib.figure import Figure import threadi…