欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

JAVA操作elastic?search的詳細(xì)過程

 更新時(shí)間:2024年08月05日 15:51:40   作者:_BugMan  
Elasticsearch?Rest?High?Level?Client?是?Elasticsearch?官方提供的一個(gè)?Java?客戶端庫,用于與?Elasticsearch?進(jìn)行交互,本文介紹JAVA操作elastic?search的詳細(xì)過程,感興趣的朋友一起看看吧

1.環(huán)境準(zhǔn)備

本文是作者ES系列的第三篇文章,關(guān)于ES的核心概念移步:

http://www.dbjr.com.cn/article/255798.htm

關(guān)于ES的下載安裝教程以及基本使用,移步:

http://www.dbjr.com.cn/program/2934323c0.htm

在前文中,我們已經(jīng)搭建好了一個(gè)es+kibana的基礎(chǔ)環(huán)境,本文將繼續(xù)使用該環(huán)境,演示JAVA操作es。

2.ES JAVA API

Elasticsearch Rest High Level Client 是 Elasticsearch 官方提供的一個(gè) Java 客戶端庫,用于與 Elasticsearch 進(jìn)行交互。這個(gè)客戶端庫是基于 REST 風(fēng)格的 HTTP 協(xié)議,與 Elasticsearch 進(jìn)行通信,提供了更高級(jí)別的抽象,使得開發(fā)者可以更方便地使用 Java 代碼與 Elasticsearch 進(jìn)行交互。

依賴:

<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.17.3</version>
</dependency>
<dependency>
    <groupId>org.elasticsearch.client</groupId>
    <artifactId>elasticsearch-rest-high-level-client</artifactId>
    <version>7.17.3</version>
</dependency>
<dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>2.10.0</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
</dependency>
<dependency>
    <groupId>com.alibaba.fastjson2</groupId>
    <artifactId>fastjson2</artifactId>
    <version>2.0.45</version>
</dependency>

其實(shí)Rest High Level Client的使用邏輯一共就分散步:

  • 拼json
  • 創(chuàng)建request
  • client執(zhí)行request

創(chuàng)建client:

RestHighLevelClient restHighLevelClient = new RestHighLevelClient(RestClient.builder(new HttpHost("127.0.0.1",9200,"http")));

創(chuàng)建索引:

@Test
    public void createIndex() throws IOException {
        //1.拼json
        //settings
        Settings.Builder settings = Settings.builder()
                .put("number_of_shards", 3)
                .put("number_of_replicas", 1);
        //mappings
        XContentBuilder mappings = JsonXContent.contentBuilder().
                startObject().
                    startObject("properties").
                    startObject("name").
                        field("type", "text").
                    endObject().
                    startObject("age").
                        field("type", "integer").
                    endObject().
                    endObject().
                endObject();
        //2.創(chuàng)建request
        CreateIndexRequest createIndexRequest = new CreateIndexRequest("person").settings(settings).mapping(mappings);
        //3.client執(zhí)行request
        restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
    }

創(chuàng)建文檔:

@Test
    public void createDoc() throws IOException {
        Person person=new Person("1","zou",20);
        JSONObject json = JSONObject.from(person);
        System.out.println(json);
        IndexRequest request=new IndexRequest("person",null,person.getId().toString());
        request.source(json, XContentType.JSON);
        IndexResponse response = restHighLevelClient.index(request, RequestOptions.DEFAULT);
        System.out.println(response);
    }

響應(yīng)結(jié)果:

修改文檔:

@Test
    public void updateDoc() throws IOException {
        HashMap<String, Object> doc = new HashMap();
        doc.put("name","張三");
        String docId="1";
        UpdateRequest request=new UpdateRequest("person",null,docId);
        UpdateResponse response = restHighLevelClient.update(request, RequestOptions.DEFAULT);
        System.out.println(response.getResult().toString());
    }

刪除文檔:

@Test
    public void deleteDoc() throws IOException {
        DeleteRequest request=new DeleteRequest("person",null,"1");
        DeleteResponse response = restHighLevelClient.delete(request, RequestOptions.DEFAULT);
        System.out.println(response.getResult().toString());
    }

響應(yīng)結(jié)果:

搜索示例:

import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import java.io.IOException;
public class ElasticsearchSearchExample {
    public static void main(String[] args) {
        // 創(chuàng)建 RestHighLevelClient 實(shí)例,連接到 Elasticsearch 集群
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        // 構(gòu)建搜索請(qǐng)求
        SearchRequest searchRequest = new SearchRequest("your_index"); // 替換為實(shí)際的索引名稱
        // 構(gòu)建查詢條件
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        searchSourceBuilder.query(QueryBuilders.matchAllQuery()); // 查詢所有文檔
        // 設(shè)置一些可選參數(shù)
        searchSourceBuilder.from(0); // 設(shè)置起始索引,默認(rèn)為0
        searchSourceBuilder.size(10); // 設(shè)置返回結(jié)果的數(shù)量,默認(rèn)為10
        searchSourceBuilder.timeout(new TimeValue(5000)); // 設(shè)置超時(shí)時(shí)間,默認(rèn)為1分鐘
        // 將查詢條件設(shè)置到搜索請(qǐng)求中
        searchRequest.source(searchSourceBuilder);
        try {
            // 執(zhí)行搜索請(qǐng)求
            SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
            // 處理搜索響應(yīng)
            System.out.println("Search took: " + searchResponse.getTook());
            // 獲取搜索結(jié)果
            SearchHits hits = searchResponse.getHits();
            System.out.println("Total hits: " + hits.getTotalHits().value);
            // 遍歷搜索結(jié)果
            for (SearchHit hit : hits.getHits()) {
                System.out.println("Document ID: " + hit.getId());
                System.out.println("Source: " + hit.getSourceAsString());
            }
        } catch (IOException e) {
            // 處理異常
            e.printStackTrace();
        } finally {
            try {
                // 關(guān)閉客戶端連接
                client.close();
            } catch (IOException e) {
                // 處理關(guān)閉連接異常
                e.printStackTrace();
            }
        }
    }
}

請(qǐng)注意,上述示例中的 your_index 應(yīng)該替換為你實(shí)際的 Elasticsearch 索引名稱。這個(gè)示例使用了簡單的 matchAllQuery,你可以根據(jù)實(shí)際需求構(gòu)建更復(fù)雜的查詢條件。在搜索響應(yīng)中,你可以獲取到搜索的結(jié)果以及相關(guān)的元數(shù)據(jù)。

3.Spring Boot操作ES

在 Spring Boot 中操作 Elasticsearch 通常使用 Spring Data Elasticsearch,以標(biāo)準(zhǔn)的JPA的模式來操作ES。

依賴:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.6.x</version> <!-- 選擇一個(gè)與Elasticsearch 7.17.3兼容的Spring Boot版本 -->
</parent>
<dependencies>
    <!-- Spring Boot Starter Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!-- Spring Data Elasticsearch -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
    </dependency>
    <!-- Spring Boot Starter Test (for testing) -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</dependencies>
application.properties配置:

spring.data.elasticsearch.cluster-nodes=localhost:9200

實(shí)體類:

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.elasticsearch.annotations.FieldType;
import java.util.Date;
@Document(indexName = "blogpost_index")
public class BlogPost {
    @Id
    private String id;
    @Field(type = FieldType.Text)
    private String title;
    @Field(type = FieldType.Text)
    private String content;
    @Field(type = FieldType.Keyword)
    private String author;
    @Field(type = FieldType.Date)
    private Date publishDate;
    // 構(gòu)造函數(shù)、getter和setter
    public BlogPost() {
    }
    public BlogPost(String id, String title, String content, String author, Date publishDate) {
        this.id = id;
        this.title = title;
        this.content = content;
        this.author = author;
        this.publishDate = publishDate;
    }
    // 省略 getter 和 setter 方法
}

dao層:

import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface BlogPostRepository extends ElasticsearchRepository<BlogPost, String> {
    // 你可以在這里定義自定義查詢方法
}

service層:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class BlogPostService {
    private final BlogPostRepository blogPostRepository;
    @Autowired
    public BlogPostService(BlogPostRepository blogPostRepository) {
        this.blogPostRepository = blogPostRepository;
    }
    public BlogPost save(BlogPost blogPost) {
        return blogPostRepository.save(blogPost);
    }
    public Optional<BlogPost> findById(String id) {
        return blogPostRepository.findById(id);
    }
    public List<BlogPost> findAll() {
        return (List<BlogPost>) blogPostRepository.findAll();
    }
    public void deleteById(String id) {
        blogPostRepository.deleteById(id);
    }
}

到此這篇關(guān)于JAVA操作elastic search的文章就介紹到這了,更多相關(guān)Java操作elastic search內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java網(wǎng)絡(luò)編程中的TCP/UDP詳解

    Java網(wǎng)絡(luò)編程中的TCP/UDP詳解

    這篇文章主要介紹了Java網(wǎng)絡(luò)編程中的TCP/UDP詳解,網(wǎng)絡(luò)編程是指編寫運(yùn)行在多個(gè)設(shè)備的程序,這些設(shè)備都通過網(wǎng)絡(luò)連接起來,java.net 包中 J2SE 的 API 包含有類和接口,它們提供低層次的通信細(xì)節(jié),需要的朋友可以參考下
    2023-12-12
  • Mybatis-Plus的使用詳解

    Mybatis-Plus的使用詳解

    這篇文章主要介紹了Mybatis-Plus的使用詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • 詳解利用Spring加載Properties配置文件

    詳解利用Spring加載Properties配置文件

    本篇文章主要介紹了詳解利用Spring加載Properties配置文件,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2017-04-04
  • 如何用Spring發(fā)送電子郵件

    如何用Spring發(fā)送電子郵件

    這篇文章主要介紹了如何用Spring發(fā)送電子郵件,幫助大家更好的理解和使用Java,感興趣的朋友可以了解下
    2021-02-02
  • java書店系統(tǒng)畢業(yè)設(shè)計(jì) 總體設(shè)計(jì)(1)

    java書店系統(tǒng)畢業(yè)設(shè)計(jì) 總體設(shè)計(jì)(1)

    這篇文章主要介紹了java書店系統(tǒng)畢業(yè)設(shè)計(jì),第一步系統(tǒng)總體設(shè)計(jì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2016-10-10
  • SpringBoot中使用@Value注解注入詳解

    SpringBoot中使用@Value注解注入詳解

    這篇文章主要介紹了SpringBoot中的@Value注入詳解,在SpringBoot中,@Value注解可以注入一些字段的普通屬性,并且會(huì)自動(dòng)進(jìn)行類型轉(zhuǎn)換,本文對(duì)這些類型進(jìn)行總結(jié),需要的朋友可以參考下
    2023-08-08
  • SpringBoot如何優(yōu)雅的處理全局異常

    SpringBoot如何優(yōu)雅的處理全局異常

    這篇文章主要給大家介紹了關(guān)于SpringBoot如何優(yōu)雅的處理全局異常的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用SpringBoot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-05-05
  • 解決maven項(xiàng)目tomcat啟動(dòng)失敗war exploded:Error during artifact deploym問題

    解決maven項(xiàng)目tomcat啟動(dòng)失敗war exploded:Error during 

    在SpringMVC項(xiàng)目中,使用war和warexploded兩種部署方式可能會(huì)導(dǎo)致不同的路徑問題,從而出現(xiàn)404錯(cuò)誤,war模式將項(xiàng)目打包上傳,而warexploded模式則保持文件夾結(jié)構(gòu)上傳,開發(fā)時(shí)建議使用warexploded模式,方便利用Update classes and resources功能自動(dòng)更新
    2024-10-10
  • Java定時(shí)/延時(shí)任務(wù)之Timer用法詳解

    Java定時(shí)/延時(shí)任務(wù)之Timer用法詳解

    在?Java?Development?Kit?(JDK)?中,java.util.Timer?是一個(gè)用于調(diào)度任務(wù)的工具類,本文主要來和大家聊聊Timer的用法,有需要的小伙伴可以了解下
    2024-12-12
  • mybatis雙重foreach如何實(shí)現(xiàn)遍歷map中的兩個(gè)list數(shù)組

    mybatis雙重foreach如何實(shí)現(xiàn)遍歷map中的兩個(gè)list數(shù)組

    本文介紹了如何解析前端傳遞的JSON字符串并在Java后臺(tái)動(dòng)態(tài)構(gòu)建SQL查詢條件,首先,通過JSONArray.fromObject()將JSON字符串轉(zhuǎn)化為JSONArray對(duì)象,遍歷JSONArray,從中提取name和infos,構(gòu)建成Map對(duì)象用于Mybatis SQL映射
    2024-09-09

最新評(píng)論