溫馨提示×

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

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

springboot2.1.6集成elasticsearch6.4.3如何實(shí)現(xiàn)全文搜索

發(fā)布時(shí)間:2021-06-30 17:33:28 來源:億速云 閱讀:456 作者:chen 欄目:大數(shù)據(jù)

這篇文章主要講解了“springboot2.1.6集成elasticsearch6.4.3如何實(shí)現(xiàn)全文搜索”,文中的講解內(nèi)容簡(jiǎn)單清晰,易于學(xué)習(xí)與理解,下面請(qǐng)大家跟著小編的思路慢慢深入,一起來研究和學(xué)習(xí)“springboot2.1.6集成elasticsearch6.4.3如何實(shí)現(xiàn)全文搜索”吧!

由于項(xiàng)目需要elasticsearch做全文搜索,其基本介紹如下:

簡(jiǎn)介:ElasticSearch是一個(gè)基于Lucene的搜索服務(wù)器。它提供了一個(gè)分布式多用戶能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java開發(fā)的,并作為Apache許可條款下的開放源碼發(fā)布,是當(dāng)前流行的企業(yè)級(jí)搜索引擎。設(shè)計(jì)用于云計(jì)算中,能夠達(dá)到實(shí)時(shí)搜索,穩(wěn)定,可靠,快速,安裝使用方便。官方客戶端在Java、.NET(C#)、PHP、Python、Apache Groovy、Ruby和許多其他語(yǔ)言中都是可用的。根據(jù)DB-Engines的排名顯示,Elasticsearch是最受歡迎的企業(yè)搜索引擎,其次是Apache Solr,也是基于Lucene。

springboot整合elasticsearch常有方式主要有三種:

1.Java API
基于TCP和ES通信,官方已經(jīng)明確表示在ES 7.0版本中將棄用TransportClient客戶端,且在8.0版本中完全移除它,所以不提倡。
2.REST Client
上面的方式1是基于TCP和ES通信的(而且TransPort將來會(huì)被拋棄……),官方也給出了基于HTTP的客戶端REST Client(推薦使用),官方給出來的REST Client有Java Low Level REST Client和Java Hight Level REST Client兩個(gè),前者兼容所有版本的ES,后者是基于前者開發(fā)出來的,只暴露了部分API.
3.spring-data-elasticsearch
除了上述方式,Spring也提供了本身基于SpringData實(shí)現(xiàn)的一套方案spring-data-elasticsearch

spring-data-elasticsearch集成Es這種方式,封裝了比較常見的es操作,和JPA操作數(shù)據(jù)庫(kù)一樣便捷,只需要繼承 ElasticsearchRepository就可以實(shí)現(xiàn)常見的es操作了。

public interface UserESRepository extends ElasticsearchRepository<UserBean, Long> {}

在測(cè)試的過程中,鼓搗了兩天多都好無進(jìn)展,始終報(bào)如下錯(cuò)誤:

Caused by: org.elasticsearch.client.transport.NoNodeAvailableException: None of the configured nodes are available: [{#transport#-1}{kgdgqCDKRlm9rjdj2B_s8A}{47.89.250.94}{47.89.250.94:9300}]

看了很多博客,基本上說是端口和cluster-name 不對(duì)應(yīng)的造成的,可是改了之后還是報(bào)錯(cuò),后來才知道版本不對(duì)應(yīng)造成的。

springboot2.1.6集成elasticsearch6.4.3如何實(shí)現(xiàn)全文搜索

1.使用IDEA創(chuàng)建springboot項(xiàng)目

  • 依賴文件build.gradle:

plugins {
	id 'org.springframework.boot' version '2.1.6.RELEASE'
	id 'java'
}

apply plugin: 'io.spring.dependency-management'

group = 'com.example'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '1.8'

repositories {
	mavenCentral()
}

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-data-elasticsearch'
	implementation 'org.springframework.boot:spring-boot-starter-web'
	testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
  • 配置文件application.yml:

spring:
  data:
    elasticsearch:
      cluster-name: EStest
      cluster-nodes: 127.0.0.1:9300



server:
  port: 8080

2.下載elasticsearch

  • 到官網(wǎng):https://www.elastic.co/cn/downloads/past-releases/官網(wǎng)

可以下載歷史版本,最新版本為(7.2.0),不建議使用最新的

springboot2.1.6集成elasticsearch6.4.3如何實(shí)現(xiàn)全文搜索

我使用的版本:

springboot版本Elasticsearch版本
2.1.66.4.3

下載后文件目錄:

springboot2.1.6集成elasticsearch6.4.3如何實(shí)現(xiàn)全文搜索

  • 進(jìn)入config文件夾后,修改 elasticsearch.yml :

# ======================== Elasticsearch Configuration =========================
#
# NOTE: Elasticsearch comes with reasonable defaults for most settings.
#       Before you set out to tweak and tune the configuration, make sure you
#       understand what are you trying to accomplish and the consequences.
#
# The primary way of configuring a node is via this file. This template lists
# the most important settings you may want to configure for a production cluster.
#
# Please consult the documentation for further information on configuration options:
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
#
# ---------------------------------- Cluster -----------------------------------
#
# Use a descriptive name for your cluster:
#
cluster.name: EStest
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
#
node.name: node-1
#
# Add custom attributes to the node:
#
#node.attr.rack: r1
#
# ----------------------------------- Paths ------------------------------------
#
# Path to directory where to store the data (separate multiple locations by comma):
#
#path.data: /path/to/data
#
# Path to log files:
#
#path.logs: /path/to/logs
#
# ----------------------------------- Memory -----------------------------------
#
# Lock the memory on startup:
#
#bootstrap.memory_lock: true
#
# Make sure that the heap size is set to about half the memory available
# on the system and that the owner of the process is allowed to use this
# limit.
#
# Elasticsearch performs poorly when the system is swapping the memory.
#
# ---------------------------------- Network -----------------------------------
#
# Set the bind address to a specific IP (IPv4 or IPv6):
#
network.host: 0.0.0.0
#
# Set a custom port for HTTP:
#
http.port: 9200
#
# For more information, consult the network module documentation.
#
# --------------------------------- Discovery ----------------------------------
#
# Pass an initial list of hosts to perform discovery when new node is started:
# The default list of hosts is ["127.0.0.1", "[::1]"]
#
#discovery.zen.ping.unicast.hosts: ["host1", "host2"]
#
# Prevent the "split brain" by configuring the majority of nodes (total number of master-eligible nodes / 2 + 1):
#
#discovery.zen.minimum_master_nodes:
#
# For more information, consult the zen discovery module documentation.
#
# ---------------------------------- Gateway -----------------------------------
#
# Block initial recovery after a full cluster restart until N nodes are started:
#
#gateway.recover_after_nodes: 3
#
# For more information, consult the gateway module documentation.
#
# ---------------------------------- Various -----------------------------------
#
# Require explicit names when deleting indices:
#
#action.destructive_requires_name: true


http.cors.enabled: true
http.cors.allow-origin: "*"
node.master: true
node.data: true
提示: 這里的cluster.name: EStest 要與application.yml中的cluster-name: EStest保持一致
  • 啟動(dòng) elasticsearch 腳本,雙擊即可啟動(dòng)

springboot2.1.6集成elasticsearch6.4.3如何實(shí)現(xiàn)全文搜索

  • 在瀏覽器中輸入http://localhost:9200/ ,出現(xiàn)如下就說明啟動(dòng)成功:

springboot2.1.6集成elasticsearch6.4.3如何實(shí)現(xiàn)全文搜索

3.添加數(shù)據(jù)到es,并實(shí)現(xiàn)搜索

<1>創(chuàng)建實(shí)體:

package com.example.demo;


import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.experimental.Accessors;
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.io.Serializable;


/*
 *@Description: Blog實(shí)體
 *@ClassName: BlogModel
 *@Author: zzq
 *@Date: 2019/7/19 17:47
 *@Version: 1.0
 */
@Data
@Accessors(chain = true)

@Document(indexName = "blog", type = "user")
public class BlogModel implements Serializable {

    private static final long serialVersionUID = 1L;

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

    //@Field(type = FieldType.Date, format = DateFormat.basic_date)

    public BlogModel(){

    }
    public BlogModel(Long id, String title) {
        this.id = id;
        this.title = title;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    @Override
    public String toString() {
        return "BlogModel{" +
                "id='" + id + '\'' +
                ", title='" + title + '\'' +
                '}';
    }
}

<2> 創(chuàng)建操作數(shù)據(jù)的Repository

package com.example.demo;

import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

/*
 *@Description: 數(shù)據(jù)倉(cāng)庫(kù)
 *@ClassName: BlogRepository
 *@Author: zzq
 *@Date: 2019/7/19 17:48
 *@Version: 1.0
 */
public interface BlogRepository extends ElasticsearchRepository<BlogModel, String> {
}

<3>創(chuàng)建controller

package com.example.demo;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.GetMapping;


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


/*
 *@Description: controller
 *@ClassName: BlogController
 *@Author: zzq
 *@Date: 2019/7/19 17:49
 *@Version: 1.0
 */
@RestController
@RequestMapping("/blog")
@Repository
public class BlogController {
    @Autowired
    private BlogRepository blogRepository;
    @GetMapping("/save")
    public String add() {

        BlogModel blogModel = new BlogModel();
        blogModel.setTitle("superheros");
        blogRepository.save(blogModel);
        return "ok";
    }
    private String title = "";
    @GetMapping("/get")
    public String get(){

        Iterable<BlogModel> list = (List<BlogModel>) blogRepository.findAll();
        list.forEach(blogModel -> {
            title += blogModel.toString() + "\n";
        });
        return title;
    }
}

<4>啟動(dòng)入口

package com.example.demo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ElasticsearchApplication {

	public static void main(String[] args) {
		SpringApplication.run(ElasticsearchApplication.class, args);
	}

}

4.結(jié)果

springboot2.1.6集成elasticsearch6.4.3如何實(shí)現(xiàn)全文搜索

查詢:

dspringboot2.1.6集成elasticsearch6.4.3如何實(shí)現(xiàn)全文搜索

感謝各位的閱讀,以上就是“springboot2.1.6集成elasticsearch6.4.3如何實(shí)現(xiàn)全文搜索”的內(nèi)容了,經(jīng)過本文的學(xué)習(xí)后,相信大家對(duì)springboot2.1.6集成elasticsearch6.4.3如何實(shí)現(xiàn)全文搜索這一問題有了更深刻的體會(huì),具體使用情況還需要大家實(shí)踐驗(yàn)證。這里是億速云,小編將為大家推送更多相關(guān)知識(shí)點(diǎn)的文章,歡迎關(guān)注!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI