91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringBoot框架如何集成ElasticSearch

發布時間:2021-11-02 11:44:44 來源:億速云 閱讀:212 作者:小新 欄目:開發技術

這篇文章主要為大家展示了“SpringBoot框架如何集成ElasticSearch”,內容簡而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領大家一起研究并學習一下“SpringBoot框架如何集成ElasticSearch”這篇文章吧。

依賴

SpringBoot版本:2.4.2

 <dependencies>
        <!--lombok-->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
		  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
            <scope>true</scope>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
    </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>2020.0.1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2021.1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

先了解一下curl方式操作es

SpringBoot框架如何集成ElasticSearch

與SpringBoot集成

配置類

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.elasticsearch.client.ClientConfiguration;
import org.springframework.data.elasticsearch.client.RestClients;
import org.springframework.data.elasticsearch.config.AbstractElasticsearchConfiguration;
@Configuration
public class ElasticsearchConfig extends AbstractElasticsearchConfiguration {
    @Override
    @Bean
    public RestHighLevelClient elasticsearchClient() {
        final ClientConfiguration clientConfiguration = ClientConfiguration.builder()
                .connectedTo("localhost:9200")
                .build();
        return RestClients.create(clientConfiguration).rest();
    }
}

實體類

import lombok.Data;
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;
@Data
@Document(indexName = "product", shards = 3, replicas = 1)
public class Product {
    //必須有 id,這里的 id 是全局唯一的標識,等同于 es 中的"_id"
    @Id
    private Long id;//商品唯一標識
    /**
     * type : 字段數據類型
     * analyzer : 分詞器類型
     * index : 是否索引(默認:true)
     * Keyword : 短語,不進行分詞
     */
    @Field(type = FieldType.Text, analyzer = "ik_max_word")
    private String title;//商品名稱
    @Field(type = FieldType.Keyword)
    private String category;//分類名稱
    @Field(type = FieldType.Double)
    private Double price;//商品價格
    @Field(type = FieldType.Keyword, index = false)
    private String images;//圖片地址
}

測試例子

 

@RestController
@RequestMapping
public class TestESController {
    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    @Resource
    ProductMapper productMapper;
    @GetMapping
    public void createIndex() {
        //創建索引,系統初始化會自動創建索引
        System.out.println("創建索引");
    }
    @DeleteMapping
    public void deleteIndex() {
        //創建索引,系統初始化會自動創建索引
        boolean flg = elasticsearchRestTemplate.deleteIndex(Product.class);
        System.out.println("刪除索引 = " + flg);
    }
    @PostMapping
    public void save(){
        Product product = new Product();
        product.setId(1L);
        product.setTitle("華為手機");
        product.setCategory("手機");
        product.setPrice(2999.0);
        product.setImages("http://www.atguigu/hw.jpg");
        productMapper.save(product);
    }
    @PutMapping
    public void update(){
        Product product = new Product();
        product.setId(1L);
        product.setTitle("小米 2 手機");
        product.setCategory("手機");
        product.setPrice(9999.0);
        product.setImages("http://www.atguigu/xm.jpg");
        productMapper.save(product);
    }
    @GetMapping("/findById")
    public void findById(){
        Product product = productMapper.findById(1L).get();
        System.out.println(product);
    }
    @GetMapping("/findAll")
    public void findAll(){
        Iterable<Product> products = productMapper.findAll();
        for (Product product : products) {
            System.out.println(product);
        }
    }
    //刪除
    @DeleteMapping("/delDocument")
    public void delete(){
        Product product = new Product();
        product.setId(1L);
        productMapper.delete(product);
    }
    //批量新增
    @PostMapping("/addBatch")
    public void saveAll(){
        List<Product> productList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            Product product = new Product();
            product.setId(Long.valueOf(i));
            product.setTitle("["+i+"]小米手機");
            product.setCategory("手機");
            product.setPrice(1999.0+i);
            product.setImages("http://www.atguigu/xm.jpg");
            productList.add(product);
        }
        productMapper.saveAll(productList);
    }
    //分頁查詢
    @GetMapping("/findByPageable")
    public void findByPageable(){
        //設置排序(排序方式,正序還是倒序,排序的 id)
        Sort sort = Sort.by(Sort.Direction.DESC,"id");
        int currentPage=0;//當前頁,第一頁從 0 開始, 1 表示第二頁
        int pageSize = 5;//每頁顯示多少條
        //設置查詢分頁
        PageRequest pageRequest = PageRequest.of(currentPage, pageSize,sort);
        //分頁查詢
        Page<Product> productPage = productMapper.findAll(pageRequest);
        for (Product Product : productPage.getContent()) {
            System.out.println(Product);
        }
    }
}

RestHighLevelClient直接操作

這些操作,就是javaApi,和上圖中,通過http方式和es交互式類似的

索引操作

/**
 * 這里時測試,開發時:通過 ESTemplate操作。Spring進行了封裝
 */
@Slf4j
public class ESIndexTestCase {
    public static void main(String[] args) throws IOException {
        // 創建客戶端
        RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200)));
        // 創建索引
        // CreateIndexRequest indexRequest = new CreateIndexRequest("book");
        // CreateIndexResponse indexResponse = esClient.indices().create(indexRequest, RequestOptions.DEFAULT);
        // boolean acknowledged = indexResponse.isAcknowledged();
        // log.error("響應{}",acknowledged);
        // 查詢索引
        // GetIndexRequest getIndexRequest = new GetIndexRequest("book");
        // GetIndexResponse getIndexResponse = esClient.indices().get(getIndexRequest, RequestOptions.DEFAULT);
        // log.info("getAliases:{}",getIndexResponse.getAliases());
        // log.info("getMappings:{}",getIndexResponse.getMappings());
        // log.info("getSettings:{}",getIndexResponse.getSettings());
        // 刪除索引
        AcknowledgedResponse deleteRes = esClient.indices().delete(new DeleteIndexRequest("book"), RequestOptions.DEFAULT);
        boolean delAck = deleteRes.isAcknowledged();
        log.error("delAck:{}",delAck);
        esClient.close();
    }
}

文檔操作

@Slf4j
public class ESDocmentTestCase {
    public static void main(String[] args) throws IOException {
        // 創建客戶端
        RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200)));
        // 新增文檔
        // IndexRequest indexRequest = new IndexRequest("user");
        // indexRequest.id("1001");       
        // // 準備文檔
        // User user = new User();
        // user.setName("張三");
        // user.setAge(22);
        // user.setSex("男");        
        // String userJson = JSONObject.toJSONString(user);
        // indexRequest.source(userJson, XContentType.JSON);
        // IndexResponse indexResponse = esClient.index(indexRequest, RequestOptions.DEFAULT);
        // log.error("getResult:==========>:{}",indexResponse.getResult());
        // 批量新增文檔
        BulkRequest bulkRequest = new BulkRequest();
        bulkRequest.add(new IndexRequest("user").id("2001").source(XContentType.JSON,"name","張三","age","40","sex","男"));
        bulkRequest.add(new IndexRequest("user").id("2002").source(XContentType.JSON,"name","222","age","10","sex","女"));
        bulkRequest.add(new IndexRequest("user").id("2003").source(XContentType.JSON,"name","33333","age","20","sex","男"));
        bulkRequest.add(new IndexRequest("user").id("2004").source(XContentType.JSON,"name","111","age","30","sex","男"));
        bulkRequest.add(new IndexRequest("user").id("2005").source(XContentType.JSON,"name","2222","age","31","sex","女"));
        BulkResponse bulkResponse = esClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        log.error("getResult:==========>:{}",bulkResponse.getTook());
        // 更新文檔(全量更新,局部更新)

        // UpdateRequest updateRequest = new UpdateRequest("user", "1001");
        // updateRequest.doc("sex","dddddd");
        // UpdateResponse updateResponse = esClient.update(updateRequest, RequestOptions.DEFAULT);
        // log.error("getResult:==========>:{}",updateResponse.getResult());

        // 根據_id查詢文檔
        // GetRequest getRequest = new GetRequest("user", "1001");
        // GetResponse getResponse = esClient.get(getRequest, RequestOptions.DEFAULT);
        // log.error("getResult:==========>:{}",getResponse.getSource());

        // 根據_id 刪除數據
        // DeleteRequest deleteRequest = new DeleteRequest("user", "1001");
        // DeleteResponse deleteResponse = esClient.delete(deleteRequest, RequestOptions.DEFAULT);
        // log.error("getResult:==========>:{}",deleteResponse.getResult());

        // 批量刪除(和批量新增類似)
        esClient.close();
    }
}

檢索操作

@Slf4j
public class EsSearchTest {
    public static void main(String[] args) throws IOException {
        // 創建客戶端
        RestHighLevelClient esClient = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200)));
        // 查詢所有
        // SearchRequest searchRequest = new SearchRequest("user");
        // SearchSourceBuilder queryBuilder = new SearchSourceBuilder().query(QueryBuilders.matchAllQuery());
        // queryBuilder.from(0);
        // queryBuilder.size(4);
        // queryaBuilder.sort("age", SortOrder.DESC);
        // SearchRequest sourceRequest = searchRequest.source(queryBuilder);
        // SearchResponse searchResponse = esClient.search(sourceRequest, RequestOptions.DEFAULT);
        // log.error("getHits:======>{}", searchResponse.getHits().getTotalHits());
        // searchResponse.getHits().forEach(hit -> System.out.println(hit.getSourceAsString()));
        // 2-組合查詢
        // SearchRequest searchRequest = new SearchRequest("user");
        // BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        // // 這里就是組合條件。和mysql where 組合類似
        // boolQueryBuilder.should(QueryBuilders.matchQuery("age","30"));
        // boolQueryBuilder.should(QueryBuilders.matchQuery("age","40"));
        // SearchSourceBuilder sourceBuilder = new SearchSourceBuilder().query(boolQueryBuilder);
        // searchRequest.source(sourceBuilder);
        // SearchResponse searchResponse = esClient.search(searchRequest, RequestOptions.DEFAULT);
        // searchResponse.getHits().forEach(hit -> System.err.println(hit.getSourceAsString()));
        // 3-范圍查詢
        // SearchRequest searchRequest = new SearchRequest("user");
        // SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        // RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("age");
        // rangeQuery.gte("30");
        // sourceBuilder.query(rangeQuery);
        // searchRequest.source(sourceBuilder);
        // SearchResponse searchResponse = esClient.search(searchRequest, RequestOptions.DEFAULT);
        // searchResponse.getHits().forEach(hit -> System.out.println(hit.getSourceAsString()));
        //4-模糊查詢+高亮
        SearchRequest searchRequest = new SearchRequest("user");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        FuzzyQueryBuilder fuzzyQuery = QueryBuilders.fuzzyQuery("name", "張三");
        sourceBuilder.query(fuzzyQuery);
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<font color='red'>");
        highlightBuilder.postTags("</font>");
        highlightBuilder.field("name");
        sourceBuilder.highlighter(highlightBuilder);
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = esClient.search(searchRequest, RequestOptions.DEFAULT);
        searchResponse.getHits().forEach(System.out::println);
        // 5-聚合查詢
        esClient.close();
    }
}

以上是“SpringBoot框架如何集成ElasticSearch”這篇文章的所有內容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內容對大家有所幫助,如果還想學習更多知識,歡迎關注億速云行業資訊頻道!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

秦安县| 铜川市| 井陉县| 巩留县| 家居| 武威市| 边坝县| 鄂州市| 寿宁县| 客服| 阿拉善盟| 商南县| 安达市| 衡阳县| 英超| 建宁县| 雅江县| 太谷县| 万年县| 攀枝花市| 丰台区| 石楼县| 锦州市| 淅川县| 洞口县| 吉安县| 奉新县| 邵武市| 辽宁省| 科尔| 洛扎县| 云浮市| 凤山县| 平阳县| 杂多县| 灵台县| 万安县| 门头沟区| 广汉市| 当涂县| 荃湾区|