SpringBoot は Elasticsearch を統合します (最新かつ最も完全で効率的なインストールと使用)

1. Elasticsearch関連のプラグインをインストールする

1. バージョンを選択します

使用される Elasticsearch のバージョンと SpringBoot で使用されるバージョンの間の不一致によって引き起こされる問題を回避するには、一貫したバージョンを使用するようにしてください。次の表は対応関係を示しています。

ここに画像の説明を挿入します
私の SpringBoot バージョン:

<parent>
   <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.15</version>
    <relativePath />
</parent>

したがって、対応する Elasticsearch バージョンは 7.12.0 として選択されます。

2. Elasticsearchをインストールする

さまざまなバージョンの Elasticsearch をダウンロード
Elasticsearch7.12.0 公式ウェブサイトをダウンロード

  1. 上にリンクされているインストール パッケージをダウンロードします
  2. 任意のディレクトリに解凍します
  3. /bin/elasticsearch.bat を開始します
  4. インストール結果を確認するには、Web ページで「localhost:9200」と入力し、以下の画面が表示されれば成功です。

ここに画像の説明を挿入します

現時点で問題が発生している可能性があります。localhost を使用してアクセスできますが、IP を使用してアクセスできません
Elasticsearch インストール ディレクトリの /config/elasticsearch.yml を変更する必要があります58 行目に次の設定を追加します

network.bind_host: 0.0.0.0

追加が完了したら、es サービスを再起動します。クラッシュの問題が発生する可能性があります。
問題が発生した場合: ブートストラップ チェックの失敗 [1]/[1]: デフォルトの検出設定運用環境での使用には適していません。[discovery.seed_hosts、discovery.seed_providers、cluster.initial_master_nodes] の少なくとも 1 つを構成する必要があります
。 Elasticsearch インストール ディレクトリの行位置

#cluster.initial_master_nodes: ["node-1", "node-2"]

注釈を解放し、次のように変更します。

cluster.initial_master_nodes: ["node-1"]

3.ノードのインストール

es5 以降では、node と grunt のインストールが必要なため、head プラグインをインストールするための前提条件として、これら 2 つの項目を設定する必要があります。

ノード ダウンロード アドレス環境に応じたノード バージョンをダウンロードしてインストールします。

インストール プロセスが完了したら、DOS ウィンドウでインストールが成功したかどうかを確認します。次のコマンドを使用します。node -v。次のスクリーンショットが表示されれば、インストールは成功です。

ここに画像の説明を挿入します

4.gruntをインストールする

ノードのインストール パスで、コマンド npm install -g grunt-cli を使用して grunt をインストールします。インストールが完了したら、 grunt
-version コマンドを使用して、インストールが成功したかどうかを確認します。次のスクリーンショットが表示され、インストールが成功したことが示されます。

ここに画像の説明を挿入します

5.es-headプラグインをインストールする

ES のインデックスとデータを便利に表示

es-headのダウンロードアドレス

elasticsearch-head-master を解凍します
このディレクトリに cmd コマンドを入力し、npm install を実行します。

ここに画像の説明を挿入します

完了後にコマンドを実行しますgrunt サーバー
grunt サーバーが起動コマンドです < a i=4> エラーが発生した場合

ここに画像の説明を挿入します

cmd を使用して実行を続行しますnpm install grunt --save-dev。これにより、最新バージョンが package.json に追加されます。

ここに画像の説明を挿入します

エラーが報告されない場合は、コマンド ウィンドウが表示されます。

ここに画像の説明を挿入します

ブラウザ入力 127.0.0.1:9100

ここに画像の説明を挿入します

実際には、ここで elasticsearch に接続することはできず、クロスドメインの問題を解決する必要があります。
フロントエンドとバックエンドは別々に開発されているため、クロスドメインの問題になるため、サーバー側で CORS を構成する必要があります。
Elasticsearch インストール ディレクトリの /config/elasticsearch.yml を変更し、次の設定を追加します。

http.cors.enabled: true
http.cors.allow-origin: "*"
http.cors.allow-credentials: true
http.cors.allow-headers: Content-Type,Accept,Authorization,x-requested-with
#http.cors.allow-headers: "*"

ESサービスを再起動します

ここに画像の説明を挿入します

6.キバナのインストール

目的: REST API を通じて ES のデバッグを容易にする。

kibana 公式 7.12.0 ダウンロード アドレス
kibana 中国語コミュニティ ダウンロード アドレス

  1. 解凍する
  2. 修改 kibana-7.12.0-windows-x86_64/config/kibana.yml 32行
  3. elasticsearch.hosts に変更します: ["http://127.0.0.1:9200"]
  4. 保存後、bin/kibana.bat を実行します。
  5. ブラウザで kibana ホームページにアクセスホームページ リンク

ここに画像の説明を挿入します

開発ツールへの直接アクセス:開発ツール

ここに画像の説明を挿入します

IP を使用して kibana にアクセスする場合は、変更する必要があります。kibana-7.12.0-windows-x86_64/config/kibana.yml 7 行 kibana 中国語版を使用したい場合は、変更する必要があります。 i18n.locale: “zh-CN ” 最後の行kibana-7.12.0-windows-x86_64/config/kibana.yml
server.host: “0.0.0.0” に変更します

7.ikワードセグメンターをインストールする

注: ダウンロードした ik word seminter のバージョン番号は、インストールされている elasticsearch のバージョンと一致している必要があります。

ダウンロードした ik ワード セグメンターを Elasticsearch インストール ディレクトリ/plugins/ik に解凍します。

ここに画像の説明を挿入します

  1. ikワードセグメンタをテストする
  2. elasticsearchを再起動します
  3. キバナを再起動する
  4. kibana の開発ツールにアクセスしてコマンド テストを実行します開発ツール
  5. コマンドを実行: GET _analyze{ “analyzer”: “ik_max_word”, “text”: “割引アップまたはダウン”}
  6. 実行結果は以下の通り
    ここに画像の説明を挿入します

2. SpringBoot と Elasticarch を統合する

1.pom.xml

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.15</version>
    <relativePath />
</parent>
<!--springBoot2.5.15对应Elasticsearch7.12.0版本-->
<!--elasticsearch-->
<dependency>
    <groupId>org.elasticsearch</groupId>
    <artifactId>elasticsearch</artifactId>
    <version>7.12.0</version>
</dependency>

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

2.アプリケーション.yml

spring:
	elasticsearch:
       rest:
            uris: 192.168.1.36:9200
            connection-timeout: 1s
            read-timeout: 30s

3.ElasticSearch(エンティティクラス)

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;

//@Document 文档对象 (索引信息、文档类型 )
@Document(indexName="blog3")
@Data
public class ElasticSearch {
    
    

    //@Id 文档主键 唯一标识
    @Id
    //@Field 每个文档的字段配置(类型、是否分词、是否存储、分词器 )
    @Field(store=true, index = false,type = FieldType.Integer)
    private Integer id;

    @Field(index=true,analyzer="ik_smart",store=true,searchAnalyzer="ik_smart",type = FieldType.Text)
    private String title;

    @Field(index=true,analyzer="ik_smart",store=true,searchAnalyzer="ik_smart",type = FieldType.Text)
    private String content;

    @Field(index=true,store=true,type = FieldType.Double)
    private Double price;
}

4.エラスティックサーチリポジトリ

import com.economics.project.es.domain.ElasticSearch;
import org.springframework.data.elasticsearch.annotations.Highlight;
import org.springframework.data.elasticsearch.annotations.HighlightField;
import org.springframework.data.elasticsearch.annotations.HighlightParameters;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
import java.util.List;

@Repository
public interface ElasticSearchRepository extends ElasticsearchRepository<ElasticSearch, Integer> {
    
    

    /**
     * 查询内容标题查询
     * @param title 标题
     * @param content 内容
     * @return 返回关键字高亮的结果集
     */
    @Highlight(
            fields = {
    
    @HighlightField(name = "title"), @HighlightField(name = "content")},
            parameters = @HighlightParameters(preTags = {
    
    "<span style='color:red'>"}, postTags = {
    
    "</span>"}, numberOfFragments = 0)
    )
    List<SearchHit<ElasticSearch>> findByTitleOrContent(String title, String content);

}

5.エラスティックサーチサービス

import com.economics.project.es.domain.ElasticSearch;
import org.springframework.data.elasticsearch.core.SearchHit;
import java.util.List;

public interface ElasticSearchService {
    
    

    //保存和修改
    void save(ElasticSearch article);
    //查询id
    ElasticSearch findById(Integer id);
    //删除指定ID数据
    void   deleteById(Integer id);

    long count();
    
    boolean existsById(Integer id);

    List<SearchHit<ElasticSearch>> findByTitleOrContent(String title, String content);

}

6.ElasticSearchServiceImpl

import com.economics.project.es.domain.ElasticSearch;
import com.economics.project.es.service.ElasticSearchService;
import com.economics.project.es.service.ElasticSearchRepository;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;

@Service
public class ElasticSearchServiceImpl implements ElasticSearchService {
    
    

    @Resource
    private ElasticSearchRepository ElasticSearchRepository;


    @Override
    public void save(ElasticSearch ElasticSearch) {
    
    
        ElasticSearchRepository.save(ElasticSearch);
    }

    @Override
    public ElasticSearch findById(Integer id) {
    
    
        return ElasticSearchRepository.findById(id).orElse(new ElasticSearch());
    }

    @Override
    public void deleteById(Integer id) {
    
    
        ElasticSearchRepository.deleteById(id);
    }

    @Override
    public long count() {
    
    
        return ElasticSearchRepository.count();
    }

    @Override
    public boolean existsById(Integer id) {
    
    
        return ElasticSearchRepository.existsById(id);
    }

    @Override
    public List<SearchHit<ElasticSearch>> findByTitleOrContent(String title, String content) {
    
    
        return ElasticSearchRepository.findByTitleOrContent(title,content);
    }

}

7.エステテスト

import com.economics.EconomicsApplication;
import com.economics.project.es.domain.ElasticSearch;
import com.economics.project.es.service.ElasticSearchService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.Resource;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest(classes = EconomicsApplication.class)
public class EsTest {
    
    

    @Resource
    private ElasticSearchService elasticSearchService;

    @Resource
    private ElasticsearchRestTemplate elasticsearchRestTemplate;
    /**创建索引和映射*/
    @Test
    public void createIndex(){
    
    

//        elasticsearchTemplate.createIndex(ElasticSearch.class);
//        elasticsearchTemplate.putMapping(ElasticSearch.class);
    }

    /**添加文档或者修改文档(以id为准)*/
    @Test
    public void saveElasticSearch(){
    
    
        ElasticSearch elasticSearch = new ElasticSearch();
        elasticSearch.setId(1);
        elasticSearch.setTitle("SpringData ElasticSearch");
        elasticSearch.setContent("Spring Data ElasticSearch 基于 spring data API 简化 elasticSearch操作,将原始操作elasticSearch的客户端API 进行封装 \n" +
                "    Spring Data为Elasticsearch Elasticsearch项目提供集成搜索引擎");
        elasticSearchService.save(elasticSearch);
    }
    @Test
    public void findById(){
    
    
        ElasticSearch byId = elasticSearchService.findById(1);
        System.out.println(byId);
    }
    @Test
    public void deleteById(){
    
    
        elasticSearchService.deleteById(100);

    }
    @Test
    public void count(){
    
    
        long count = elasticSearchService.count();
        System.out.println(count);
    }
    @Test
    public void existsById(){
    
    
        boolean b = elasticSearchService.existsById(102);

        System.out.println(b);
    }
    @Test
    public void findByTitleOrContent(){
    
    
        List<SearchHit<ElasticSearch>> byTitleOrContent = elasticSearchService.findByTitleOrContent("xxxxxxSpringData","elasticSearch");
        for (SearchHit<ElasticSearch> elasticSearchService : byTitleOrContent) {
    
    
            List<String> title = elasticSearchService.getHighlightField("title");
            System.out.println(title);
            List<String> content = elasticSearchService.getHighlightField("content");
            System.out.println(content);

        }
    }
}

8. カスタマイズされたクエリ方法

キーワード 説明する 方法
そして Field1 と Field2 に基づいてデータを取得します findByTitleAndContent(文字列タイトル,文字列コンテンツ);
または Field1 または Field2 に基づいてデータを取得します findByTitleOrContent(文字列タイトル,文字列コンテンツ);
フィールドに基づいてデータを取得する findByTitle(文字列タイトル);
ない フィールドに基づいて逆のデータを取得する findByTitleNot(文字列タイトル)
指定した範囲のデータを取得する findByPriceBetween(倍の価格 1, 倍の価格 2);
等しいより小さい 指定した値以下のデータを取得します findByPriceLessThan(倍の価格);
大きい以上等しい 指定した値以上のデータを取得します findByPriceGreaterThan(倍の価格);
前に 価格で探す
価格後検索
のように 比較的馴染みのあるデータ 名前で検索
で始まります xxで始まるデータ findByNameStartingWith(文字列名);
で終わる xxで終わるデータ findByNameEndingWith(文字列名);
含む/含む データが含まれています findByNameContaining(文字列名);
複数の値のマッチング findByNameIn(コレクション名)
水泳 複数の値が一致しません findByNameNotIn(コレクション名)
注文方法 ソートされたデータ findByxxxxxOrderByNameDesc(String xxx );

おすすめ

転載: blog.csdn.net/whatevery/article/details/132062101