ES的java操作

ES的java操作

一、添加依賴

在pom文件中添加依賴包

    <dependencies><dependency><groupId>org.elasticsearch</groupId><artifactId>elasticsearch</artifactId><version>7.8.0</version></dependency><!-- elasticsearch 客戶端 --><dependency><groupId>org.elasticsearch.client</groupId><artifactId>elasticsearch-rest-high-level-client</artifactId><version>7.8.0</version></dependency><!-- elasticsearch 依賴 2.x 的 log4j --><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-api</artifactId><version>2.11.1</version></dependency><dependency><groupId>org.apache.logging.log4j</groupId><artifactId>log4j-core</artifactId><version>2.11.1</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.9.9</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version></dependency></dependencies>

二、基本框架

package com.wbb.es;import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;public class Elasticsearch_Client {public static void main(String[] args) throws Exception {// 創建ES客戶端RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));/*中間要做的事兒*/// 關閉ES客戶端client.close();}
}

三、索引操作

3.1 創建

創建索引 test_java

// 創建索引
CreateIndexRequest request = new CreateIndexRequest("test_java");
CreateIndexResponse createIndexResponse = client.indices().create(request, RequestOptions.DEFAULT);// 響應狀態
boolean acknowledged = createIndexResponse.isAcknowledged();
System.out.println("操作轉態 :" + acknowledged);

3.2 查看

// 查詢索引
GetIndexRequest request = new GetIndexRequest("test_java");
// 發送請求
GetIndexResponse response = client.indices().get(request,RequestOptions.DEFAULT);
System.out.println("aliases:"+response.getAliases());
System.out.println("mappings:"+response.getMappings());
System.out.println("settings:"+response.getSettings());

輸出內容

aliases:{test_java=[]}
mappings:{test_java=org.elasticsearch.cluster.metadata.MappingMetadata@e2fe038d}
settings:{test_java={"index.creation_date":"1739345734421","index.number_of_replicas":"1","index.number_of_shards":"1","index.provided_name":"test_java","index.uuid":"R-2HSigUTCSH1mG9kiowrg","index.version.created":"7080099"}}

3.2 刪除索引

// 刪除索引 - 請求對象
DeleteIndexRequest request = new DeleteIndexRequest("test_java");
// 發送請求,獲取響應
AcknowledgedResponse response = client.indices().delete(request,RequestOptions.DEFAULT);
// 操作結果
System.out.println("操作結果 : " + response.isAcknowledged());

四、文檔操作

創建javabean

快捷鍵:定義屬性后 ctrl + shift + a,選擇 Generate …alt + insert,選擇對應的getter和setter

package com.wbb.es;public class test_es {private String name;private Integer age;private String sex;public void setName(String name) {this.name = name;}public void setAge(Integer age) {this.age = age;}public void setSex(String sex) {this.sex = sex;}public String getName() {return name;}public Integer getAge() {return age;}public String getSex() {return sex;}}

4.1創建

4.1.1 添加單個文檔

在索引 test_java下添加文檔編號為001的文檔

// 1、新增文檔 - 請求對象
IndexRequest request = new IndexRequest();
// 2、設置索引及唯一性標識
request.index("test_java").id("001");
// 3、創建數據對象
Test_es test_es = new Test_es();
test_es.setName("tianxuanzhizi");
test_es.setAge(30);
test_es.setSex("男");
ObjectMapper objectMapper = new ObjectMapper();
String productJson = objectMapper.writeValueAsString(test_es);
// 4、添加文檔數據,數據格式為 JSON 格式
request.source(productJson, XContentType.JSON);
// 5、客戶端發送請求,獲取響應對象
IndexResponse response = client.index(request, RequestOptions.DEFAULT);
// 打印結果信息
System.out.println("_index:" + response.getIndex());
System.out.println("_id:" + response.getId());
System.out.println("_result:" + response.getResult());

輸出信息

_index:test_java
_id:001
_result:CREATED
4.1.2 添加多個文檔
//創建批量新增請求對象
BulkRequest request = new BulkRequest();
request.add(new IndexRequest().index("test_java").id("001").source(XContentType.JSON, "name","tianxuanzhizi001", "age", 30, "sex", "男"));
request.add(new IndexRequest().index("test_java").id("002").source(XContentType.JSON, "name","tianxuanzhizi002", "age", 31, "sex", "女"));
//客戶端發送請求,獲取響應對象
BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
//打印結果信息
System.out.println("took:" + responses.getTook());
System.out.println("items:" + responses.getItems());

輸出結果

took:198ms
items:[Lorg.elasticsearch.action.bulk.BulkItemResponse;@5609159b

4.2 修改

修改 test_java索引下,id為 001 的文檔,sex為”未知“

// 1、修改文檔 - 請求對象
UpdateRequest request = new UpdateRequest();
// 2、配置修改參數
request.index("test_java").id("001");
// 3、設置請求體,對數據進行修改
request.doc(XContentType.JSON, "sex", "未知");
// 客戶端發送請求,獲取響應對象
UpdateResponse response = client.update(request, RequestOptions.DEFAULT);
System.out.println("_index:" + response.getIndex());
System.out.println("_id:" + response.getId());
System.out.println("_result:" + response.getResult());

輸出信息

_index:test_java
_id:001
_result:UPDATED

4.3 查看

//1.創建請求對象
GetRequest request = new GetRequest().index("test_java").id("001");
//2.客戶端發送請求,獲取響應對象
GetResponse response = client.get(request, RequestOptions.DEFAULT);
//3.打印結果信息
System.out.println("_index:" + response.getIndex());
System.out.println("_type:" + response.getType());
System.out.println("_id:" + response.getId());
System.out.println("source:" + response.getSourceAsString());

輸出結果

_index:test_java
_type:_doc
_id:001
source:{"name":"tianxuanzhizi","age":30,"sex":"未知"}

4.4 刪除

4.4.1 刪除單個文檔
//1、創建請求對象
DeleteRequest request = new DeleteRequest().index("test_java").id("001");
//2、客戶端發送請求,獲取響應對象
DeleteResponse response = client.delete(request, RequestOptions.DEFAULT);
//打印信息
System.out.println(response.toString());

輸出信息

DeleteResponse[index=test_java,type=_doc,id=001,version=3,result=deleted,shards=ShardInfo{total=2, successful=1, failures=[]}]
4.4.2 刪除多個文檔
//創建批量刪除請求對象
BulkRequest request = new BulkRequest();
request.add(new DeleteRequest().index("test_java").id("001"));
request.add(new DeleteRequest().index("test_java").id("002"));
//客戶端發送請求,獲取響應對象
BulkResponse responses = client.bulk(request, RequestOptions.DEFAULT);
//打印結果信息
System.out.println("took:" + responses.getTook());
System.out.println("items:" + responses.getItems());
System.out.println("items:" + responses.getItems());

輸出信息

took:201ms
items:[Lorg.elasticsearch.action.bulk.BulkItemResponse;@7c9d8e2
items:[Lorg.elasticsearch.action.bulk.BulkItemResponse;@7c9d8e2

4.5 查詢

4.5.1 查詢的基本框架
package com.wbb.es;import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;public class Elasticsearch_Client {public static void main(String[] args) throws Exception {// 創建ES客戶端RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));// 創建搜索請求對象SearchRequest request = new SearchRequest();request.indices("test_java");// 構建查詢的請求體SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();/*查詢設置*/request.source(sourceBuilder); SearchResponse response = client.search(request, RequestOptions.DEFAULT);// 查詢匹配SearchHits hits = response.getHits();System.out.println("took:" + response.getTook());System.out.println("timeout:" + response.isTimedOut());System.out.println("total:" + hits.getTotalHits());System.out.println("MaxScore:" + hits.getMaxScore());System.out.println("========doc=========");for (SearchHit hit : hits) {//輸出每條查詢的結果信息System.out.println(hit.getSourceAsString());}// 關閉ES客戶端client.close();}
}
4.5.1 查詢所有文檔
sourceBuilder.query(QueryBuilders.matchAllQuery());

輸出信息

took:2ms
timeout:false
total:2 hits
MaxScore:1.0
========doc=========
{"name":"tianxuanzhizi001","age":30,"sex":"男"}
{"name":"tianxuanzhizi002","age":31,"sex":"女"}
4.5.2 按照字段名進行查詢
sourceBuilder.query(QueryBuilders.termQuery("age", "30"));

輸出

took:3ms
timeout:false
total:1 hits
MaxScore:1.0
========doc=========
{"name":"tianxuanzhizi001","age":30,"sex":"男"}
4.5.3 分頁查詢
sourceBuilder.query(QueryBuilders.matchAllQuery());
// 分頁查詢
// 分頁起始位置(第一條數據的順序號)
sourceBuilder.from(0);
// 每頁顯示多少條
sourceBuilder.size(2);

輸出

took:2ms
timeout:false
total:2 hits
MaxScore:1.0
========doc=========
{"name":"tianxuanzhizi001","age":30,"sex":"男"}
{"name":"tianxuanzhizi002","age":31,"sex":"女"}
4.5.4 排序查詢

按照年齡排序

sourceBuilder.query(QueryBuilders.matchAllQuery());
sourceBuilder.sort("age", SortOrder.ASC);
4.5.5 過濾字段
sourceBuilder.query(QueryBuilders.matchAllQuery());
// 只查看 name 和 age
String[] excludes = {}; 
String[] includes = {"name", "age"}; 
sourceBuilder.fetchSource(includes, excludes); 
4.5.6 組合查詢
// 構建查詢的請求體
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
// 必須包含
boolQueryBuilder.must(QueryBuilders.matchQuery("age", "30"));
// 一定不含
boolQueryBuilder.mustNot(QueryBuilders.matchQuery("name", "bug"));
// 可能包含
boolQueryBuilder.should(QueryBuilders.matchQuery("sex", "男"));sourceBuilder.query(boolQueryBuilder);

輸出結果

took:3ms
timeout:false
total:1 hits
MaxScore:1.6931472
========doc=========
{"name":"tianxuanzhizi001","age":30,"sex":"男"}
4.5.7 范圍查詢
RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
// 大于等于
rangeQuery.gte("30");
// 小于等于
rangeQuery.lte("40");
sourceBuilder.query(rangeQuery);
4.5.8 模糊查詢
sourceBuilder.query(QueryBuilders.fuzzyQuery("name","tianxuanzhizi").fuzziness(Fuzziness.ONE));
4.5.9 高亮查詢
//構建查詢方式:高亮查詢
TermsQueryBuilder termsQueryBuilder = QueryBuilders.termsQuery("name","tianxuanzhizi001");
//設置查詢方式
sourceBuilder.query(termsQueryBuilder);
//構建高亮字段
HighlightBuilder highlightBuilder = new HighlightBuilder();
highlightBuilder.preTags("<font color='red'>");//設置標簽前綴
highlightBuilder.postTags("</font>");//設置標簽后綴
highlightBuilder.field("name");//設置高亮字段
//設置高亮構建對象
sourceBuilder.highlighter(highlightBuilder);

輸出前設置高亮顏色

//打印高亮結果 Map<String, HighlightField> highlightFields = hit.getHighlightFields()System.out.println(highlightFields);;

查詢結果

took:171ms
timeout:false
total:1 hits
MaxScore:1.0
========doc=========
{name=[name], fragments[[<font color='red'>tianxuanzhizi001</font>]]}
4.5.9 聚合查詢

查詢最大年齡

sourceBuilder.aggregation(AggregationBuilders.max("maxAge").field("age"));

輸出response

System.out.println(response);    

輸出結果

{"took":2,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":2,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"test_java","_type":"_doc","_id":"001","_score":1.0,"_source":{"name":"tianxuanzhizi001","age":30,"sex":"男"}},{"_index":"test_java","_type":"_doc","_id":"002","_score":1.0,"_source":{"name":"tianxuanzhizi002","age":31,"sex":"女"}}]},"aggregations":{"max#maxAge":{"value":31.0}}}
4.5.10 分組聚合

按性別分組

sourceBuilder.aggregation(AggregationBuilders.terms("age_groupby").field("age"));

輸出response

System.out.println(response);    

輸出結果

{"took":1,"timed_out":false,"_shards":{"total":1,"successful":1,"skipped":0,"failed":0},"hits":{"total":{"value":2,"relation":"eq"},"max_score":1.0,"hits":[{"_index":"test_java","_type":"_doc","_id":"001","_score":1.0,"_source":{"name":"tianxuanzhizi001","age":30,"sex":"男"}},{"_index":"test_java","_type":"_doc","_id":"002","_score":1.0,"_source":{"name":"tianxuanzhizi002","age":31,"sex":"女"}}]},"aggregations":{"lterms#age_groupby":{"doc_count_error_upper_bound":0,"sum_other_doc_count":0,"buckets":[{"key":30,"doc_count":1},{"key":31,"doc_count":1}]}}}

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

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

相關文章

DeepSeek 從入門到精通學習指南,2025清華大學《DeepSeek從入門到精通》正式發布104頁pdf版超全解析

DeepSeek 是一款強大的 AI 搜索引擎&#xff0c;廣泛應用于企業級數據檢索和分析。無論您是初學者還是有經驗的用戶&#xff0c;掌握 DeepSeek 的使用都能為您的工作帶來極大的便利。本文將從入門到精通&#xff0c;詳細介紹如何學習和使用 DeepSeek。 鏈接: https://pan.baid…

飛書專欄-TEE文檔

CSDN學院課程連接&#xff1a;https://edu.csdn.net/course/detail/39573

2025.2.11——一、[極客大挑戰 2019]PHP wakeup繞過|備份文件|代碼審計

題目來源&#xff1a;BUUCTF [極客大挑戰 2019]PHP 目錄 一、打開靶機&#xff0c;整理信息 二、解題思路 step 1&#xff1a;目錄掃描、爆破 step 2&#xff1a;代碼審計 1.index.php 2.class.php 3.flag.php step 3&#xff1a;繞過__wakeup重置 ?編輯 三、小結…

AI大模型(DeepSeek)科研應用、論文寫作、數據分析與AI繪圖學習

【介紹】 在人工智能浪潮中&#xff0c;2024年12月中國公司研發的 DeepSeek 橫空出世以驚艷全球的姿態&#xff0c;成為 AI領域不可忽視的力量!DeepSeek 完全開源&#xff0c;可本地部署&#xff0c;無使用限制&#xff0c;保護用戶隱私。其次&#xff0c;其性能強大&#xff…

考研操作系統----操作系統的概念定義功能和目標(僅僅作為王道嗶站課程講義作用)

目錄 操作系統的概念定義功能和目標 操作系統的四個特征 操作系統的分類 ?編輯 操作系統的運行機制 系統調用 操作系統體系結構 操作系統引導 虛擬機 操作系統的概念定義功能和目標 什么是操作系統&#xff1a; 操作系統是指控制和管理整個計算機系統的軟硬件資源&…

DeepSeek 突然來襲,AI 大模型變革的危機與轉機藏在哪?

隨著人工智能技術的飛速發展&#xff0c;大模型領域不斷涌現出具有創新性的成果。DeepSeek 的橫空出世&#xff0c;為 AI 大模型領域帶來了新的變革浪潮。本文將深入探討 DeepSeek 出現后 AI 大模型面臨的危機與轉機。 沖沖沖&#xff01;&#xff01;&#xff01; 目錄 一、…

JVM的類加載器

什么是類加載器&#xff1f; 類加載器&#xff1a;JVM只會運行二進制文件&#xff0c;類加載器的作用就是將字節碼文件加載到JVM中&#xff0c;從而Java 程序能夠啟動起來。 類加載器有哪些&#xff1f; 啟動類加載器(BootStrap ClassLoader):加載JAVA HOME/jre/lib目錄下的庫…

web前端開發中vscode常用的快捷鍵

1.快速復制一行 快捷鍵&#xff1a; shiftalt 下箭頭(上箭頭) 或者 ctrlc 然后 ctrlv 2.選定多個相同的單詞 快捷鍵&#xff1a; ctrl d 先雙擊選定一個單詞&#xff0c;然后按下 ctrl d 可以往下依次選擇相同的單詞。 這樣同時修改相同的單詞 3.全局替換某單詞 當我們一個…

C與C++的區別,類型轉換,引用

1.從C到C 語言的區別 C語言 編譯性語言 面向過程語言靈活 移植性好 效率高shell 解釋性語言 面向過程語言Linux運維C 編譯性語言 面向對象面向對象語言效率最高的 應用領域&#xff1a;系統開發(APP開發&#xff0c;服務器開發)&#xff0c;引擎開發&#xff0c;游戲開發&…

SQL-leetcode—1581. 進店卻未進行過交易的顧客

1581. 進店卻未進行過交易的顧客 表&#xff1a;Visits -------------------- | Column Name | Type | -------------------- | visit_id | int | | customer_id | int | -------------------- visit_id 是該表中具有唯一值的列。 該表包含有關光臨過購物中心的顧客的信息。 …

Jenkins 部署 之 Mac 一

Jenkins 部署 之 Mac 一 一.Jenkins 部署依賴 JDK 環境 查看 Mac JDK 環境&#xff0c;如果沒有安裝&#xff0c;先安裝 打開終端輸入命令:java -version Mac安裝配置 JDK 二. 檢查 HomeBrew 安裝 檢查 HomeBrew 是否安裝&#xff0c;終端輸入命令:brew -v Mac安裝HomeB…

鴻蒙HarmonyOS NEXT開發:優化用戶界面性能——組件復用(@Reusable裝飾器)

文章目錄 一、概述二、原理介紹三、使用規則四、復用類型詳解1、標準型2、有限變化型2.1、類型1和類型2布局不同&#xff0c;業務邏輯不同2.2、類型1和類型2布局不同&#xff0c;但是很多業務邏輯公用 3、組合型4、全局型5、嵌套型 一、概述 組件復用是優化用戶界面性能&#…

【AI大模型】Ollama部署本地大模型DeepSeek-R1,交互界面Open-WebUI,RagFlow構建私有知識庫

文章目錄 DeepSeek介紹公司背景核心技術產品與服務應用場景優勢與特點訪問與體驗各個DeepSeek-R系列模型的硬件需求和適用場景 Ollama主要特點優勢應用場景安裝和使用配置環境變量總結 安裝open-webui下載和安裝docker desktop配置鏡像源安裝open-webui運行和使用 RagFlow介紹主…

更加通用的Hexo多端部署原理及實現,適用于各種系統之間

本文推薦在作者的個人博客網站閱讀&#xff1a;shenying.online 一、故事背景 故事發生在大學上學期間&#xff08;而不是寒假&#xff09;。上學期間&#xff0c;宿舍條件極其惡劣&#xff0c;半夜斷電、空間狹小。我們大學垃圾條件使用游戲本的種種弊端被無限放大&#xff1…

開源、免費項目管理工具比較:2025最新整理30款

好用的開源、免費版項目管理系統有&#xff1a;1.Redmine&#xff1b;2. Taiga&#xff1b;3. OpenProject&#xff1b; 4.ProjectLibre&#xff1b; 5.GanttProject&#xff1b; 6.Tuleap&#xff1b; 7.Trac&#xff1b;8. Phabricator&#xff1b; 9.Notion&#xff1b; 10.…

組織結構改革:激活企業活力的 “源頭活水”

難以適應市場變化、內部溝通與協作不暢、決策效率低下、運營成本增加、人才流失嚴重、員工士氣下降、戰略目標難以實現……企業如何根據市場環境變化和自身發展需求&#xff0c;靈活調整組織框架&#xff0c;賦能企業的持續健康發展&#xff1f; 某國有投資建設集團旗下的二級…

oracle中decode怎么轉換成pg

對于 PostgreSQL 中的 Oracle DECODE 函數&#xff0c;可以使用 CASE 表達式或聯合。CASE 表達式根據條件返回第一個匹配的結果&#xff0c;語法為&#xff1a;CASE WHEN 條件 THEN 結果 ELSE 結果 END。聯合通過 UNION ALL 操作符組合多個 SELECT 語句&#xff0c;返回一個包含…

Mac之JDK安裝

Mac之JDK安裝 一.安裝 jdk 打開終端輸入命令:java -version 查看是否已安裝 JDK Oracle 官方下載地址 根據自己Mac 系統安裝 查看 Mac 系統&#xff0c;打開中斷命令&#xff0c;輸入: uname -a Compressed Archive 是壓縮文檔&#xff0c;下載的是一個 .tar.gz 壓縮包 D…

【含文檔+PPT+源碼】基于Python的全國景區數據分析以及可視化實現

項目介紹 本課程演示的是一款基于Python的全國景區數據分析以及可視化實現&#xff0c;主要針對計算機相關專業的正在做畢設的學生與需要項目實戰練習的 Java 學習者。 包含&#xff1a;項目源碼、項目文檔、數據庫腳本、軟件工具等所有資料 帶你從零開始部署運行本套系統 該…

Unity中快速制作2D沙雕動畫:流程編

Unity中快速制作2D沙雕動畫&#xff08;搞笑/無厘頭風格&#xff09;&#xff0c;通過以下方案實現低成本、高成效的開發流程&#xff0c;結合夸張的動作、滑稽的物理效果和魔性音效&#xff1a; 1. 角色與素材設計 核心原則&#xff1a;丑萌即正義&#xff0c;越怪越好&#…