国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Springboot實戰(zhàn)之spring-boot-starter-data-elasticsearch搭建ES搜索接口

這篇具有很好參考價值的文章主要介紹了Springboot實戰(zhàn)之spring-boot-starter-data-elasticsearch搭建ES搜索接口。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報違法"按鈕提交疑問。

Springboot實戰(zhàn)之spring-boot-starter-data-elasticsearch搭建ES搜索接口

本教程是本人親自實戰(zhàn)的,然后運(yùn)行起來的全部步驟。

準(zhǔn)備工作

環(huán)境
Elasticsearch 7.15.2
Kibana 7.15.2
springboot 2.6.4 以及對應(yīng)的spring-boot-starter-web和spring-boot-starter-data-elasticsearch
fastjson 1.2.97

  1. 安裝好Elasticsearch7.15.2以及對應(yīng)的Kibana。
  2. 去Springboot Start 新建項目

在Kibana中新建索引book

使用 devtools 創(chuàng)建

# 新增索引
PUT book
{
  "settings" : {
      "number_of_shards" : 5,
      "number_of_replicas" : 0,
      "refresh_interval": "5s", 
      "index.mapping.ignore_malformed": true 
  },
  "mappings": {
    "properties": {
      "title": {
        "type": "text",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_max_word"
      },
      "author": {
        "type": "text",
        "analyzer": "ik_max_word",
        "search_analyzer": "ik_max_word"
      },
      "postDate": {
        "type": "keyword"
      }
    }
  }
}

number_of_shards 數(shù)據(jù)分片 默認(rèn)為5
number_of_replicas 數(shù)據(jù)備份數(shù),如果只有一臺機(jī)器,建議設(shè)置為0,避免索引一直處于yellow狀態(tài)

查看是否創(chuàng)建成功

HEAD book

返回如下,即為創(chuàng)建索引成功

200 - OK

搜素 book 里面的信息

POST book/_search
{
  "from": 0,
  "size": 20
}

新建springboot項目

Springboot Start 新建項目
Springboot實戰(zhàn)之spring-boot-starter-data-elasticsearch搭建ES搜索接口
點(diǎn)擊generate就會獲取一個zip的包。這個就是生成的項目哦。

打開項目

項目完成之后的完整目錄:
Springboot實戰(zhàn)之spring-boot-starter-data-elasticsearch搭建ES搜索接口

pom.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.6.4</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.wumeng</groupId>
	<artifactId>esapi</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>esapi</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<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.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<optional>true</optional>
		</dependency>


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


		<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.79</version>
		</dependency>



	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
				<configuration>
					<excludes>
						<exclude>
							<groupId>org.projectlombok</groupId>
							<artifactId>lombok</artifactId>
						</exclude>
					</excludes>
				</configuration>
			</plugin>
		</plugins>
	</build>


	<repositories>
		<repository>
			<id>ali-maven</id>
			<url>http://maven.aliyun.com/nexus/content/groups/public</url>
		</repository>
	</repositories>

</project>

application.properties 文件

# ELASTICSEARCH (ElasticsearchProperties)

# Whether to enable Elasticsearch repositories.
spring.data.elasticsearch.repositories.enabled=true

spring.elasticsearch.uris=http://192.168.0.119:9200
spring.elasticsearch.username=elastic
spring.elasticsearch.password=12345678
spring.elasticsearch.socket-timeout=30

修改成自己的用戶名和密碼哦

BookBean.java 文件

import lombok.Builder;
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
@Builder
@Document(indexName = "book")
public class BookBean {
    private @Id String id;

    @Field(analyzer = "ik_max_word",type = FieldType.Text)
    private String title;

    @Field(analyzer = "ik_max_word",type = FieldType.Text)
    private String author;

    private String postDate;

    public  BookBean(){}

    public BookBean(String id, String title, String author, String postDate) {
        this.id = id;
        this.title = title;
        this.author = author;
        this.postDate = postDate;
    }
}

BookRepository.java 文件

import com.wumeng.esapi.model.BookBean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface BookRepository extends ElasticsearchRepository<BookBean,String> {

    //Optional<BookBean> findById(String id);

    Page<BookBean> findByAuthor(String author, Pageable pageable);

    Page<BookBean> findByTitle(String title, Pageable pageable);
    
    @Query("{\"match\": {\"title\": {\"query\": \"?0\"}}}")
    Page<BookBean> findByTitle_custom(String keyword, Pageable pageable);

}

BookService.java 文件

import com.wumeng.esapi.model.BookBean;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;

import java.util.List;
import java.util.Optional;

public interface BookService {
    Optional<BookBean> findById(String id);

    BookBean save(BookBean blog);

    void delete(BookBean blog);

    Optional<BookBean> findOne(String id);

    List<BookBean> findAll();

    Page<BookBean> findByAuthor(String author, PageRequest pageRequest);

    Page<BookBean> findByTitle(String title, PageRequest pageRequest);

    List<BookBean> searchByKeyword(String keyword, PageRequest pageRequest);

}

BookServiceImpl.java 文件

import com.wumeng.esapi.repository.BookRepository;
import com.wumeng.esapi.model.BookBean;
import com.wumeng.esapi.service.BookService;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class BookServiceImpl implements BookService {

    @Autowired
    @Qualifier("bookRepository")
    private BookRepository bookRepository;

    @Autowired
    private ElasticsearchOperations elasticsearchOperations;


    @Override
    public Optional<BookBean> findById(String id) {
        //CrudRepository中的方法
        return bookRepository.findById(id);
    }

    @Override
    public BookBean save(BookBean blog) {
        return bookRepository.save(blog);
    }

    @Override
    public void delete(BookBean blog) {
        bookRepository.delete(blog);
    }

    @Override
    public Optional<BookBean> findOne(String id) {
        return bookRepository.findById(id);
    }

    @Override
    public List<BookBean> findAll() {
        return (List<BookBean>) bookRepository.findAll();
    }

    @Override
    public Page<BookBean> findByAuthor(String author, PageRequest pageRequest) {
        return bookRepository.findByAuthor(author,pageRequest);
    }

    @Override
    public Page<BookBean> findByTitle(String title, PageRequest pageRequest) {
        return bookRepository.findByTitle(title,pageRequest);
    }


//    @Override
//    public Page<BookBean> searchByKeyword(String keyword, PageRequest pageRequest) {
//        return bookRepository.searchByKeyword(keyword, pageRequest);
//    }

    @Override
    public List<BookBean> searchByKeyword(String keyword, PageRequest pageRequest) {



        BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();
        // 查詢必須滿足的條件
//        boolQueryBuilder.must(QueryBuilders.termQuery("studentSex", "女"));

        // 查詢可能滿足的條件
//        boolQueryBuilder.should(QueryBuilders.termQuery("gradeNumber", "一年級"));
//        boolQueryBuilder.should(QueryBuilders.termQuery("gradeNumber", "二年級"));
//        boolQueryBuilder.should(QueryBuilders.termQuery("gradeNumber", "三年級"));//精確
        boolQueryBuilder.should(QueryBuilders.matchQuery("title",keyword));//模糊
        boolQueryBuilder.should(QueryBuilders.matchQuery("author",keyword));
        // 設(shè)置在可能滿足的條件中,至少必須滿足其中1條
//        boolQueryBuilder.minimumShouldMatch(1);

        // 必須不滿足的條件
//        boolQueryBuilder.mustNot(QueryBuilders.termQuery("age", 8));


        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        //查詢
        nativeSearchQueryBuilder.withQuery(boolQueryBuilder);
        //排序
        nativeSearchQueryBuilder.withSorts(SortBuilders.fieldSort("postDate").order(SortOrder.ASC));
        //分頁
        nativeSearchQueryBuilder.withPageable(pageRequest);
		
		//搜索
        NativeSearchQuery nativeSearchQuery = nativeSearchQueryBuilder.build();
        SearchHits<BookBean> productHits = this.elasticsearchOperations.search(nativeSearchQuery, BookBean.class, IndexCoordinates.of("book"));

        List<BookBean> productMatches = new ArrayList<BookBean>();
        productHits.forEach(searchHit->{
            productMatches.add(searchHit.getContent());
        });

        return productMatches;
    }
}

BookController.java 文件


import com.alibaba.fastjson.JSON;
import com.wumeng.esapi.service.BookService;
import com.wumeng.esapi.model.BookBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;


import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("book")
public class BookController {

    @Autowired
    private BookService bookService;

    @RequestMapping("/id/{id}")
    @ResponseBody
    public BookBean getBookById(@PathVariable String id){
        Optional<BookBean> opt =bookService.findById(id);
        BookBean book=opt.get();
        System.out.println(book);
        return book;
    }

    @RequestMapping("/save")
    @ResponseBody
    public String Save(){
        BookBean book=new BookBean("1","ES入門教程","你剛回來了","2022-03-09");
        System.out.println(book);
        bookService.save(book);

        book=new BookBean("2","ES入門教程","你剛回來了","2022-03-09");
        System.out.println(book);
        bookService.save(book);

        book=new BookBean("3","ES入門教程","你剛回來了","2022-03-09");
        System.out.println(book);
        bookService.save(book);

        return "Save success.";

    }
    @RequestMapping("/search/{keyword}")
    @ResponseBody
    public String searchBookByKeyWord(@PathVariable String keyword){
        List<BookBean> list = bookService.searchByKeyword(keyword,PageRequest.of(0,200));
        System.out.println(list);
        return JSON.toJSONString(list);
    }

}

運(yùn)行項目,跑起來。

插入信息

訪問地址:http://127.0.0.1:8080/book/save

Save success.
根據(jù)id查詢信息

訪問地址:http://127.0.0.1:8080/book/id/1

{"id":"1","title":"ES入門教程","author":"你剛回來了","postDate":"2022-03-09"}
模糊查詢titie 和author

訪問地址:http://127.0.0.1:8080/book/search/ES

[{"author":"你剛回來了","id":"2","postDate":"2022-03-09","title":"ES入門教程"},{"author":"你剛回來了","id":"1","postDate":"2022-03-09","title":"ES入門教程"}]

此次,項目簡單基本雛形已經(jīng)有了,可以繼續(xù)開發(fā)其他任務(wù)了。文章來源地址http://www.zghlxwxcb.cn/news/detail-403105.html

到了這里,關(guān)于Springboot實戰(zhàn)之spring-boot-starter-data-elasticsearch搭建ES搜索接口的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點(diǎn)擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • SpringBoot進(jìn)階教程(七十九)spring-boot-starter- 有哪些 starter類型

    spring Boot應(yīng)用啟動器基本的一共有44種,具體如下 參考文獻(xiàn):https://www.javatpoint.com/spring-boot-starters

    2024年02月05日
    瀏覽(90)
  • SpringBoot+jasypt-spring-boot-starter實現(xiàn)配置文件明文加密

    SpringBoot+jasypt-spring-boot-starter實現(xiàn)配置文件明文加密

    springboot:2.1.4.RELEASE JDK:8 jasypt-spring-boot-starter:3.0.2 Jasypt默認(rèn)算法為PBEWithMD5AndDES,該算法需要一個加密密鑰,可以在應(yīng)用啟動時指定(環(huán)境變量)。也可以直接寫入配置文件 3.1 application.properties配置文件版 加密后,可刪除jasypt.encryptor.password配置;發(fā)版時可在命令行中配置 3.2 函數(shù)

    2024年02月15日
    瀏覽(26)
  • springboot web創(chuàng)建失敗,解決Could not find artifact org.springframework.boot:spring-boot-starter-parent:pom

    springboot web創(chuàng)建失敗,解決Could not find artifact org.springframework.boot:spring-boot-starter-parent:pom

    jdk8不支持3.0以上的springboot版本,如果你在創(chuàng)建項目的時候用的是jdk8,那么我建議你在創(chuàng)建好項目之后自行再pom文件里降級,我剛開始接觸springboot時,用的是jdk11,導(dǎo)入的springboot版本是2.7.1,然后弄了差不多半天都找不到原因,然后我就擴(kuò)大了阿里云的搜索地址,自行在pom文

    2024年02月04日
    瀏覽(33)
  • springboot 發(fā)送郵件,以及郵件工具類 并且解決spring-boot-starter-mail 發(fā)送郵件附件亂碼或者文件錯亂

    1、設(shè)置系統(tǒng)值 System.setProperty(“mail.mime.splitlongparameters”, “false”); 2、 在創(chuàng)建對象的時候定義編碼格式(utf-8): MimeMessageHelper helper = new MimeMessageHelper(mes, true, “utf-8”); 3、 其次,在添加附件的時候,附件名是需要定義編碼的 helper.addAttachment(MimeUtility.encodeWord(附件名,“utf-8”

    2024年02月15日
    瀏覽(34)
  • Spring Boot - spring-boot-starter

    spring-boot-starter 當(dāng)學(xué)習(xí)Spring Boot時,可以通過一個完整的案例來理解和實踐其基本概念和功能。以下是一個簡單的Spring Boot Starter完整案例,展示了如何創(chuàng)建一個基本的Web應(yīng)用程序: 首先,創(chuàng)建一個名為pom.xml的Maven項目文件,添加以下內(nèi)容:idea或其他直接創(chuàng)建直接跳過!

    2024年02月09日
    瀏覽(26)
  • Spring Boot Starters

    Spring Boot Starters 概述 Spring Boot Starters是一系列為特定應(yīng)用場景預(yù)設(shè)的依賴管理和自動配置方案。每個Starter都是為了簡化特定類型的項目構(gòu)建和配置。例如, spring-boot-starter-web 是為創(chuàng)建基于Spring MVC的Web應(yīng)用程序而設(shè)計的。 Starter的結(jié)構(gòu) 一個典型的Starter包含以下部分: pom.xml

    2024年01月25日
    瀏覽(82)
  • 自定義Spring Boot Starter

    自定義Spring Boot Starter

    Spring Boot starter 我們知道Spring Boot大大簡化了項目初始搭建以及開發(fā)過程,而這些都是通過Spring Boot提供的starter來完成的。在實際項目中一些基礎(chǔ)模塊其本質(zhì)就是starter,所以我們需要對Spring Boot的starter有一個全面深入的了解,這是我們的必備知識。 starter介紹 spring boot 在配置

    2024年02月10日
    瀏覽(29)
  • 6. Spring Boot的starters

    6. Spring Boot的starters

    6. Spring Boot的starters(重要) 一般認(rèn)為,SpringBoot 微框架從兩個主要層面影響 Spring 社區(qū)的開發(fā)者們: 基于 Spring 框架的“約定優(yōu)先于配置(COC)”理念以及最佳實踐之路。 提供了針對日常企業(yè)應(yīng)用研發(fā)各種場景的 spring-boot-starter 自動配置依賴模塊,如此多“開箱即用”的依賴模

    2024年01月24日
    瀏覽(28)
  • Spring Boot Starter設(shè)計實現(xiàn)

    Starter 是 Spring Boot 非常重要的一個硬核功能。 通過 Starter 我們可以快速的引入一個功能或模塊,而無須關(guān)心模塊依賴的其它組件。關(guān)于配置,Spring Boot 采用“約定大于配置”的設(shè)計理念,Starter 一般都會提供默認(rèn)配置,只有當(dāng)我們有特殊需求的時候,才需要在 application.yaml 里

    2024年01月18日
    瀏覽(19)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包