高级农民工(H.F.H)
我思,故我在!(僕なら、僕ができる!)

导航

 

参考URL:

https://blog.csdn.net/cicada_smile/article/details/132308849

https://www.cnblogs.com/hualess/p/11540477.html

Elasticsearchは、オープンソースの分散型検索エンジンであり、大量のデータをリアルタイムで検索、分析することができます。主にJavaで開発されており、Apache Luceneという検索エンジンライブラリをベースにしています。

Elasticsearchの主な特徴は以下の通りです。

  1. 分散型アーキテクチャ: Elasticsearchは、データを複数のノードに分散させることができるため、データの可用性とスケーラビリティが向上します。

  2. リアルタイム検索: Elasticsearchは、データのインデックス化が非常に高速であり、リアルタイムに検索が可能です。

  3. フルテキスト検索: Elasticsearchは、高度なフルテキスト検索機能を提供しており、検索クエリの柔軟性が高いです。

  4. RESTful API: Elasticsearchは、RESTful APIを通じてデータのインデックス化、検索、管理ができるため、様々なプログラミング言語やフレームワークと連携が容易です。

  5. スキーマレス: Elasticsearchは、JSON形式のドキュメントを扱うことができ、スキーマを事前に定義する必要がありません。

  6. 高度な分析機能: Elasticsearchは、データの集計や分析を行うための機能を提供しており、ビッグデータの解析に適しています。

Elasticsearchは、ログ分析、全文検索、データ可視化など、様々な用途で利用されており、Elastic Stack(以前はELK Stackと呼ばれていた)という一連の製品群とともに、幅広い分野で活用されています。Elastic Stackには、Elasticsearchのほかに、データ収集ツールのLogstash、データ可視化ツールのKibana、軽量データシッパーのBeatsが含まれています。

 

 ■ESの環境構築

ー>ダウンロードURL:<https://www.elastic.co/cn/downloads/elasticsearch> 

cluster.name: my-es

node.name: es_node

path.data: C:/elasticsearch-8.11.1/data

path.logs: C:/elasticsearch-8.11.1/logs

network.host: 0.0.0.0

http.port: 9200

# Enable security features
# xpack.security.enabled: false

xpack.security.enrollment.enabled: true

# Enable encryption for HTTP API client connections, such as Kibana, Logstash, and Agents
xpack.security.http.ssl:
  enabled: false
  keystore.path: certs/http.p12

# Enable encryption and mutual authentication between cluster nodes
xpack.security.transport.ssl:
  enabled: true
  verification_mode: certificate
  keystore.path: certs/transport.p12
  truststore.path: certs/transport.p12
# Create a new cluster with the current node only
# Additional nodes can still join the cluster later
cluster.initial_master_nodes: ["DESKTOP-3CEF7MJ"]

# Allow HTTP API connections from anywhere
# Connections are encrypted and require user authentication
http.host: 0.0.0.0
elasticsearch.yml

ー>命令:

①パスワードの再発行:elasticsearch-reset-password -u 用户名

②パスワードの変更:elasticsearch-reset-password --username 用户名 -i

③パスワードの任意作成:elasticsearch-reset-password --url "http://localhost:9200" --username 用户名 -i

④ー1ユーザの新規:elasticsearch-users useradd 用户名

④ー2役割の設定:elasticsearch-users roles -a superuser 用户名

④ー3ユーザのPWの変更:elasticsearch-users passwd 用户名

■SpringBoot配置

①POM.xmlにPluginを追加

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

②Entity対象を追加

package com.example.springelasticsearchsample.document;

import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;

@Document(indexName = "people")
public class Person {
    @Id
    private String id;
    private String name;
    private int age;

    public String getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Person(String id, String name, int age){
        this.id=id;
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
Person.java

③データの連結を追加

package com.example.springelasticsearchsample.repo;

import com.example.springelasticsearchsample.document.Person;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;

public interface PersonRepository extends ElasticsearchRepository<Person,String> {
}

④サービスを追加

package com.example.springelasticsearchsample.service;

import com.example.springelasticsearchsample.document.Person;
import com.example.springelasticsearchsample.repo.PersonRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PersonService {
    @Autowired
    private PersonRepository personRepository;

    public void saveTestData(List<Person> lst){
        for (Person person: lst){
            personRepository.save(person);
        }
    }

    public Person save(Person person){
        return personRepository.save(person);
    }

    public Person findById(String id){
        return personRepository.findById(id).orElse(null);
    }

}

⑤コントロールを追加

package com.example.springelasticsearchsample.controller;

import com.example.springelasticsearchsample.document.Person;
import com.example.springelasticsearchsample.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/person")
public class PersonController {

    @Autowired
    private PersonService personService;

    @GetMapping("/index")
    public String index(){
        return "person";
    }


    @PostMapping("/test")
    public void saveTestData(){
        Person p1 = new Person("1","zhang3",20);
        Person p2 = new Person("2","li4",30);
        Person p3 = new Person("3","wang5",50);
        List<Person> peoplelst = Arrays.asList(p1,p2,p3);
        personService.saveTestData(peoplelst);
    }

    @PostMapping("/save")
    public Person save(@RequestBody Person book){
        return personService.save(book);
    }

    @GetMapping("/{id}")
    public Person getBookById(@PathVariable String id){
        return personService.findById(id);
    }
}

⑥実行APPを追加

package com.example.springelasticsearchsample;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan({"com.example.springelasticsearchsample.repo"})
public class SpringElasticsearchSampleApplication {

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

}

⑦YAMLを追加

server:
  port: 8080
  servlet:
    context-path: /es

spring:
  elasticsearch:
    uris: http://localhost:9200
    username: root
    password: password
  data:
    elasticsearch:
      cluster-name: my-es
      cluster-nodes: localhost:9200

■補足

ポイントの開放を設定

 

 ※:再起動が必要

==========================================

Spring BootとElasticsearchを使用した複雑なサンプルを示します。このサンプルでは、商品情報を検索するシンプルなE-commerceアプリケーションを作成します。

  1. まず、商品情報を表すProductクラスを作成します。このクラスには、商品ID、名前、説明、カテゴリ、価格、および在庫数が含まれます。
    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(indexName = "products", type = "product")
    public class Product {
    
        @Id
        private String id;
    
        @Field(type = FieldType.Text)
        private String name;
    
        @Field(type = FieldType.Text)
        private String description;
    
        @Field(type = FieldType.Keyword)
        private String category;
    
        @Field(type = FieldType.Double)
        private double price;
    
        @Field(type = FieldType.Integer)
        private int stock;
    
        // getters and setters
    }
    View Code

 

  1. 次に、ProductRepositoryインターフェースを作成します。これは、Spring Data ElasticsearchのElasticsearchRepositoryインターフェースを拡張することで実現できます。
    import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
    import org.springframework.stereotype.Repository;
    
    @Repository
    public interface ProductRepository extends ElasticsearchRepository<Product, String> {
    }
    View Code
  1. 商品情報を検索するためのサービスクラスProductServiceを作成します。このクラスでは、リポジトリインターフェースを使用して、Elasticsearchへのデータの追加、検索、更新、削除などの操作を行います。
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    @Service
    public class ProductService {
    
        @Autowired
        private ProductRepository productRepository;
    
        public Product save(Product product) {
            return productRepository.save(product);
        }
    
        public Product findById(String id) {
            return productRepository.findById(id).orElse(null);
        }
    
        public List<Product> findAll() {
            return (List<Product>) productRepository.findAll();
        }
    
        public void deleteById(String id) {
            productRepository.deleteById(id);
        }
    }
    View Code
  2. 最後に、商品情報を操作するためのRESTコントローラークラスProductControllerを作成します。このクラスでは、ProductServiceを使用して、商品情報の追加、検索、更新、削除を行うエンドポイントを提供します。
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.List;
    
    @RestController
    @RequestMapping("/api/products")
    public class ProductController {
    
        @Autowired
        private ProductService productService;
    
        @PostMapping
        public Product create(@RequestBody Product product) {
            return productService.save(product);
        }
    
        @GetMapping("/{id}")
        public Product getById(@PathVariable String id) {
            return productService.findById(id);
        }
    
        @GetMapping
        public List<Product> getAll() {
            return productService.findAll();
        }
    
        @PutMapping("/{id}")
        public Product update(@PathVariable String id, @RequestBody Product product) {
            Product existingProduct = productService.findById(id);
            if (existingProduct == null) {
                return null;
            }
            product.setId(id);
            return productService.save(product);
        }
    
        @DeleteMapping("/{id}")
        public void delete(@PathVariable String id) {
            productService.deleteById(id);
        }
    }
    View Code
  3. テストデータを追加するためのサンプルコードを示します。このコードでは、CommandLineRunnerインターフェースを実装したTestDataLoaderクラスを作成し、アプリケーションの起動時にテストデータをElasticsearchに追加します。
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.CommandLineRunner;
    import org.springframework.stereotype.Component;
    
    import java.util.Arrays;
    import java.util.List;
    
    @Component
    public class TestDataLoader implements CommandLineRunner {
    
        @Autowired
        private ProductService productService;
    
        @Override
        public void run(String... args) throws Exception {
            loadTestData();
        }
    
        private void loadTestData() {
            List<Product> products = Arrays.asList(
                    new Product("1", "Product A", "This is product A", "Electronics", 100.0, 10),
                    new Product("2", "Product B", "This is product B", "Electronics", 200.0, 20),
                    new Product("3", "Product C", "This is product C", "Books", 50.0, 30),
                    new Product("4", "Product D", "This is product D", "Clothing", 30.0, 40),
                    new Product("5", "Product E", "This is product E", "Toys", 20.0, 50)
            );
    
            for (Product product : products) {
                productService.save(product);
            }
        }
    }
    View Code

     

 ==========================================

1。まず、ProductRepositoryインターフェースにカスタム検索クエリを追加します。このクエリでは、商品名、説明、カテゴリに基づいて商品を検索します。

import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.stereotype.Repository;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.annotations.Query;

@Repository
public interface ProductRepository extends ElasticsearchRepository<Product, String> {

    @Query("{\"bool\": {\"must\": [{\"query_string\": {\"query\": \"?0\", \"fields\": [\"name^3\", \"description\", \"category^2\"]}}]}}")
    Page<Product> search(String query, Pageable pageable);
}
View Code

2.次に、ProductServiceクラスにカスタム検索クエリを使用するメソッドを追加します。

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

public class ProductService {

    // ... other methods

    public Page<Product> search(String query, int pageNumber, int pageSize) {
        Pageable pageable = PageRequest.of(pageNumber, pageSize);
        return productRepository.search(query, pageable);
    }
}
View Code

3.最後に、ProductControllerクラスにカスタム検索クエリを使用するエンドポイントを追加します。

import org.springframework.data.domain.Page;

@RestController
@RequestMapping("/api/products")
public class ProductController {

    // ... other methods

    @GetMapping("/search")
    public Page<Product> search(@RequestParam String query,
                                @RequestParam(defaultValue = "0") int pageNumber,
                                @RequestParam(defaultValue = "10") int pageSize) {
        return productService.search(query, pageNumber, pageSize);
    }
}
View Code

4.テストURL:GET /api/products/search?query=your_search_query&pageNumber=0&pageSize=10

Spring Data Elasticsearchの@Queryアノテーションを使用して、カスタム検索クエリを定義しています。このクエリは、ElasticsearchのJSON形式のクエリDSL(Domain Specific Language)を使用して記述されており、商品名、説明、カテゴリに基づいて商品情報を検索する機能を提供します。

クエリの詳細は以下の通りです。

  • bool: Boolクエリは、複数のクエリを組み合わせて検索を行うためのクエリです。この例では、mustクローズを使用して、指定された条件に一致するドキュメントを検索しています。
  • must: Mustクローズは、指定されたクエリに一致するドキュメントを検索するためのクローズです。この例では、query_stringクエリを使用しています。
  • query_string: Query Stringクエリは、複数のフィールドに対して単一のクエリ文字列を使用して検索を行うためのクエリです。この例では、queryパラメータに指定された検索文字列(?0)を使用して、namedescriptioncategoryフィールドを検索しています。
  • fields: 検索対象となるフィールドを指定します。この例では、namedescriptioncategoryフィールドが対象です。また、フィールド名の後に^記号と数字を追加することで、フィールドごとに異なるブースト値(重み付け)を設定できます。この例では、nameフィールドのブースト値を3、categoryフィールドのブースト値を2に設定しています。これにより、検索結果のスコアがフィールドごとに異なる重み付けで計算されます。

 

posted on 2023-12-04 17:04  农民工024  阅读(29)  评论(0编辑  收藏  举报