最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

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

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

http://m.fzitv.net/article/255798.htm

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

http://m.fzitv.net/program/2934323c0.htm

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

2.ES JAVA API

Elasticsearch Rest High Level Client 是 Elasticsearch 官方提供的一個 Java 客戶端庫,用于與 Elasticsearch 進(jìn)行交互。這個客戶端庫是基于 REST 風(fēng)格的 HTTP 協(xié)議,與 Elasticsearch 進(jìn)行通信,提供了更高級別的抽象,使得開發(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>

其實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 實例,連接到 Elasticsearch 集群
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(new HttpHost("localhost", 9200, "http"))
        );
        // 構(gòu)建搜索請求
        SearchRequest searchRequest = new SearchRequest("your_index"); // 替換為實際的索引名稱
        // 構(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è)置超時時間,默認(rèn)為1分鐘
        // 將查詢條件設(shè)置到搜索請求中
        searchRequest.source(searchSourceBuilder);
        try {
            // 執(zhí)行搜索請求
            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();
            }
        }
    }
}

請注意,上述示例中的 your_index 應(yīng)該替換為你實際的 Elasticsearch 索引名稱。這個示例使用了簡單的 matchAllQuery,你可以根據(jù)實際需求構(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> <!-- 選擇一個與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

實體類:

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)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Spring?Boot?Swagger3常用注解詳解與實戰(zhàn)指南

    Spring?Boot?Swagger3常用注解詳解與實戰(zhàn)指南

    Swagger是一個用于設(shè)計、構(gòu)建、文檔化和使用RESTful?Web服務(wù)的開源工具,Swagger3是Swagger的最新版本,它提供了許多新功能和改進(jìn),這篇文章主要介紹了Spring?Boot?Swagger3常用注解詳解與實戰(zhàn)指南的相關(guān)資料,需要的朋友可以參考下
    2025-10-10
  • Java?接口定義變量的示例代碼

    Java?接口定義變量的示例代碼

    文章介紹了Java接口中的變量和方法,接口中的變量必須是publicstaticfinal的,用于定義常量,而方法默認(rèn)是publicabstract的,必須由實現(xiàn)類來實現(xiàn),接口不能實例化,只能通過實現(xiàn)類來實現(xiàn)接口中的方法,本文介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
    2025-12-12
  • Spring Boot中定時任務(wù)Cron表達(dá)式的終極指南最佳實踐記錄

    Spring Boot中定時任務(wù)Cron表達(dá)式的終極指南最佳實踐記錄

    本文詳細(xì)介紹了SpringBoot中定時任務(wù)的實現(xiàn)方法,特別是Cron表達(dá)式的使用技巧和高級用法,從基礎(chǔ)語法到復(fù)雜場景,從快速啟用到調(diào)試驗證,再到常見問題的解決,涵蓋了定時任務(wù)開發(fā)的全過程,感興趣的朋友一起看看吧
    2025-03-03
  • SpringMVC中的handlerMappings對象用法

    SpringMVC中的handlerMappings對象用法

    這篇文章主要介紹了SpringMVC中的handlerMappings對象用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-09-09
  • idea配置spring項目ApplicationContext.xml自動生成實踐

    idea配置spring項目ApplicationContext.xml自動生成實踐

    本文簡述Spring配置步驟:通過文件設(shè)置添加配置項,創(chuàng)建applicationContext.xml文件,并驗證配置成功,為個人經(jīng)驗總結(jié),供開發(fā)者參考
    2025-09-09
  • 阿里Druid數(shù)據(jù)連接池引發(fā)的線上異常解決

    阿里Druid數(shù)據(jù)連接池引發(fā)的線上異常解決

    這篇文章主要為大家介紹了一次關(guān)于阿里Druid數(shù)據(jù)連接池引發(fā)的線上異常問題的解決方案,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步
    2022-03-03
  • Java并發(fā)之異步的八種實現(xiàn)方式

    Java并發(fā)之異步的八種實現(xiàn)方式

    本文主要介紹了Java并發(fā)之異步的八種實現(xiàn)方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-06-06
  • 深入理解Java的接口與抽象類

    深入理解Java的接口與抽象類

    本文主要介紹java 的接口和抽象類,對接口和抽象類進(jìn)行介紹對比,深入理解,有需要的小伙伴可以參考下
    2016-07-07
  • Java實現(xiàn)List去重的幾種方法總結(jié)

    Java實現(xiàn)List去重的幾種方法總結(jié)

    這篇文章主要為大家詳細(xì)介紹了Java中List去重的幾種常用方法總結(jié),文中的示例代碼講解詳細(xì),具有一定的學(xué)習(xí)和參考價值,需要的小伙伴可以了解一下
    2023-09-09
  • SpringBoot @ComponentScan掃描的局限性方式

    SpringBoot @ComponentScan掃描的局限性方式

    文章總結(jié):SpringBoot的@ComponentScan注解在掃描組件時存在局限性,只能掃描指定的包及其子包,無法掃描@SpringBootApplication注解自動配置的組件,使用@SpringBootApplication注解可以解決這一問題,它集成了@Configuration、@EnableAutoConfiguration
    2025-01-01

最新評論

德惠市| 翁源县| 砚山县| 申扎县| 攀枝花市| 荃湾区| 湖南省| 冀州市| 仁化县| 六安市| 唐海县| 囊谦县| 罗源县| 临沧市| 古蔺县| 大冶市| 米脂县| 东乌| 北海市| 通州市| 榆林市| 广安市| 屯留县| 福贡县| 北京市| 景谷| 广安市| 玉溪市| 浪卡子县| 竹山县| 穆棱市| 长乐市| 皋兰县| 紫金县| 东明县| 洱源县| 郧西县| 大关县| 新津县| 子长县| 毕节市|