0. 冒頭はナンセンス
0.1技術選定
Elasticsearch-7.1.12を選択します
0.2 選択の背景
選択した SpringCloud のバージョンの方が優先されるため、 SpringCloud のバージョンが決定すると、
SpringBoot のバージョン、関連コンポーネントのバージョン、Elasticsearch のバージョン、spring-data-elasticsearch のバージョンが決定されます。
0.3のバージョン関係
本番環境では安定性が求められるため、最新バージョンは使用しておりませんが、
新しいバージョンが必要な場合は、以下のリンクから入手してください。
- Spring バージョンの場合は、Spring 公式を選択します
- SpringBoot バージョンSpringBoot バージョンを選択します
- SpringDataElasticsearch バージョンspring-data-elasticsearch バージョンを選択
- SpringCloud バージョンSpringCloud バージョンを選択します
- Maven パッケージ POM Maven パッケージ
現在の学習環境では、インストールの問題を軽減し、学習意欲を刺激することを避けるために、Docker を使用して環境を構築しています。
0.4 前提条件
- (ナンセンス) Win、Mac、または Linux ベースのマシン
- (必須) Java の基本
- (必須) ドッカー
- (必須) SpringBoot の基本
- (必須) 単純なシェル
- (提案) 郵便配達員郵便配達員の正式な住所
- (推奨) SpringData の基礎
- (提案) 科学的インターネットへのアクセス
1.ソフトウェアをインストールする
1.1 イメージをプルする
docker pull elasticsearch:7.12.1
1.2 コンテナを起動する
docker run --name elasticsearch -d -e ES_JAVA_OPTS="-Xms512m -Xms512m" -e "discovery.type=single-node" -p 9200:9200 elastics
earch:7.12.1
1.3 クロスドメインアクセス
クロスドメインの構成
docker exec -it elasticsearch /bin/bash
vi config/elasticsearch.yml
修正される内容は、
cluster.name: "docker-cluster"
network.host: 0.0.0.0
http.cors.enabled: true
http.cors.allow-origin: "*"
終了し、プロンプトに従って保存します
1.4 コンテナを再起動する
docker restart elasticsearch
1.5 アクセステスト
ブラウザアクセス
http://127.0.0.1:9200
2. 補助ソフトウェア
ヘッドを取り付ける
2.1 イメージをプルする
docker pull mobz/elasticsearch-head:5
2.2 コンテナの起動
docker run --name elasticsearch-head -d -p 9100:9100 mobz/elasticsearch-head:5
2.3 アクセステスト
浏览器访问
http://127.0.0.1:9100
3. ナイフの小さなテスト
Elasticsearch へのデータの書き込みと読み取りを試してください。Postmanを
開きます
3.1 データの書き込み
別のコンテンツを変更し、さらにいくつかの項目を記述して、後続のクエリ条件を容易にすることができます。
http://127.0.0.1:9200/student/_doc/7
{
"id": 7,
"name": "wzk",
"age": "14"
}
3.2 データの読み取り
http://127.0.0.1:9200/student/_search
{
"query": {
"match": {
"name": "wzk"
}
}
}
4. 中勲百度
この章では主にクエリ、各種検索方法、検索条件、ソート、ページングなどについて説明します。
4.1 すべてをクエリする
http://127.0.0.1:9200/student/_search
{
"query": {
"match_all": {
}
}
}
4.2 全文検索
単語分割後の検索
http://127.0.0.1:9200/student/_search
{
"query": {
"match": {
"info": "oohohohoh"
}
}
}
4.3 語句検索
検索条件では単語の分割は行われません。
http://127.0.0.1:9200/student/_search
{
"query": {
"match_phrase": {
"info": "is"
}
}
}
4.4 範囲検索
数値型フィールドの範囲検索
- gt: より大きい より大きい
- gte: 以上 以上
- lt: 未満 未満
- lte: 以下以下 以下
http://127.0.0.1:9200/student/_search
{
"query": {
"range": {
"id": {
"gt": 6,
"lte": 9
}
}
}
}
4.5 フレーズ検索
単語/フレーズ検索の検索条件は単語分割分析を実行せず、検索フィールドに対応する転置インデックスで完全に一致します。
http://127.0.0.1:9200/student/_search
{
"query": {
"terms": {
"info": ["is", "who"]
}
}
}
4.6 あいまい検索
検索中にエラーが発生する可能性があります。Elasticsearch はあいまい一致のエラーを自動的に修正します。
- クエリ: 検索基準
- あいまいさ: エラー文字の最大数は 2 を超えることはできません
http://127.0.0.1:9200/student/_search
{
"query": {
"match": {
"info": {
"query": "liyi",
"fuzziness": 1
}
}
}
}
4.7 複合検索
複数の条件を組み合わせて一致する結果を検索します
- 満たさなければならない条件
- 複数の条件のいずれかを満たしている必要があります
- 満たしてはいけないmust_not条件
http://127.0.0.1:9200/student/_search
{
"query": {
"bool": {
"must": [
{
"match_phrase": {
"info": "my"
}
},
{
"match_phrase": {
"info": "name"
}
}
],
"should": [
{
"match_phrase": {
"info": "name"
}
}
],
"must_not": [
{
"match_phrase": {
"info": "wzk"
}
}
]
}
}
}
4.8 結果の並べ替え
クエリ結果をソートします。Elasticsearch
はテキスト型のフィールドデータに対して単語分割を行うため、
どの単語を使用してもテキスト型をソートするのは無理があるため、デフォルトではテキスト型のソートは許可されていません。
文字列の結果を使用して並べ替える場合は、キーワード フィールドでは単語の分割処理が実行されないため、キーワード
タイプ フィールドを並べ替えの基準として使用できます。
http://127.0.0.1:9200/student/_search
{
"query": {
"match_all": {
}
},
"sort": [
{
"id": {
"order": "desc"
}
}
]
}
4.9 ページングクエリ
実際のオンライン利用では、多数の一致結果が存在する可能性があるため、
効率を向上させるために結果をページ分割する必要があります。
http://127.0.0.1:9200/student/_search
{
"query": {
"match_all": {
}
},
"from": 0,
"size": 2
}
4.10 ハイライトクエリ
http://127.0.0.1:9200/student/_search
{
"query": {
"match": {
"info": "is"
}
},
"highlight": {
"fields": {
"info": {
"fragment_size": 100,
"number_of_fragments": 5
}
}
}
}
5.ベルトが幅広になります
SpringBoot プロジェクトで Elasticsearch を使用してプロジェクトを構築するために使用された解決策は、 SpringData を
比較的簡単に開始できるということです(私にとって、無料で学習するには十分ではないかもしれません)。
SpringBoot の基礎がすでにあることを前提としています。
ここで、混乱をすばやく解決してプロジェクトを開始します (親は 2.2.2.RELEASE です)。
5.1 プロジェクトをビルドする
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
</parent>
<dependencies>
<!-- spring-boot-web -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- elasticsearch -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!-- lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
<scope>provided</scope>
</dependency>
</dependencies>
5.2 基本構成
プロジェクトに新しいconfigディレクトリを作成し、新しい構成クラスを作成します ( @Configuration
を忘れないでください)
@Configuration
public class ElasticSearchConfig extends AbstractElasticsearchConfiguration {
@Override
public RestHighLevelClient elasticsearchClient() {
ClientConfiguration clientConfiguration = ClientConfiguration
.builder()
.connectedTo("127.0.0.1:9200")
.build();
return RestClients.create(clientConfiguration).rest();
}
}
5.3 エンティティクラス
- @Document(indexName = “student”) インデックス名はstudentです。存在しない場合は自動的に作成されます。
- @Id はインデックスです
- @Field(type = FieldType.Text、store = true) フィールド
elasticsearch に保存するオブジェクトの構造とフィールドは相互に対応させることができ、
新しいモデル フォルダーを作成し
、新しい Student オブジェクトを作成します。
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@Document(indexName = "student")
public class Student {
@Id
private Integer id;
@Field(type = FieldType.Text, store = true)
private String name;
@Field(type = FieldType.Text, store = true)
private String info;
@Field(type = FieldType.Text, store = true)
private String age;
@Field(type = FieldType.Text, store = true)
private String links;
}
5.4 インターフェースの作成
ElasticsearchRepository は、継承後に多くの既製メソッドを備えた基本クラスです。
<Student, Integer> は Student インデックスの名前です。Integer は @Id フィールドです。
新しい dao フォルダーを作成します。
新しい StudentRepository クラスを作成します。
public interface StudentRepository extends ElasticsearchRepository<Student, Integer> {
}
5.5 新しいデータ
トラブルを避けるために、ロジックはコントローラーに直接配置され、多くの既製のメソッドを提供するために
StudentRepository が SpringData に挿入されます。
@Autowired
private StudentRepository studentRepository;
@GetMapping("/addStudent")
public String addStudent() {
String name = UUID.randomUUID().toString();
name = name.replace("-", " ");
Student student = Student
.builder()
.name(name)
.links("this is a link to " + name)
.build();
studentRepository.save(student);
return "ok";
}
5.6 データのクエリ
StudentRepository を注入する
@Autowired
private StudentRepository studentRepository;
@GetMapping("/getStudent")
public List<Student> getStudent() {
Iterable<Student> dataList = studentRepository.findAll();
List<Student> resultList = new ArrayList<>();
for (Student student : dataList) {
resultList.add(student);
}
return resultList;
}
5.7 単一項目のクエリ
StudentRepository を注入する
@Autowired
private StudentRepository studentRepository;
@GetMapping("/getStudentById")
public Student getStudentById() {
Optional<Student> stuData = studentRepository.findById(11);
return stuData.orElseGet(Student::new);
}
5.8 データの変更
StudentRepository を注入する
@Autowired
private StudentRepository studentRepository;
@GetMapping("/updStudent")
public String updStudent() {
String name = UUID.randomUUID().toString();
name = name.replace("-", " ");
Student student = Student
.builder()
.id(1)
.name(name)
.links("this is a link to " + name)
.build();
studentRepository.save(student);
return "ok";
}
5.9 データの削除
StudentRepository を注入する
@Autowired
private StudentRepository studentRepository;
@GetMapping("/delStudent")
public String delStudent() {
studentRepository.deleteById(1);
return "ok";
}
6. 薄暗い照明
第 5 章では、SpringData は多くのメソッド (継承を通じて) を提供しますが、自由度が低く、クエリ条件が複雑な場合には使用できないことがわかりました
。
6.1 カスタムメソッド
まずは公式の対応
例を添付し、上記のルールに従ってご利用ください。
// 根据名字查询
List<Student> findByName(String name);
// 根据名字模糊查询
List<Student> findByNameLike(String name);
6.2 条件付きページング
Pageable pageable = PageRequest.of(0, 2); ページングクエリを実現できる
@Autowired
private StudentRepository studentRepository;
@GetMapping("/getPage")
public List<Student> getPage() {
Pageable pageable = PageRequest.of(0, 2);
Page<Student> page = studentRepository.findAll(pageable);
List<Student> dataList = page.getContent();
long number = page.getTotalElements();
int total = page.getTotalPages();
out.println("number: " + number);
out.println("total: "+ total);
return dataList;
}
6.3 カスタムページング
6.2ではページング可能なページングが使用されていますが、 6.1の方法をページングに
使用することもできます。
StudentRepository にメソッドを追加する
// 注意 Pageable page
// 这样逻辑大约变成了(方便理解 用SQL表达一下):
// select * from student where name=#{name} limit #{page.page, page.size}
Page<Student> findByNameLike(String name, Pageable page);
@Autowired
private StudentRepository studentRepository;
@GetMapping("/findByNamePage")
public List<Student> findByNamePage() {
Pageable pageable = PageRequest.of(0, 1);
// 传参 将 条件、分页 一起传入
Page<Student> data = studentRepository.findByNameLike("2", pageable);
System.out.println(data.getTotalElements());
System.out.println(data.getTotalPages());
return data.getContent();
}
6.4 クエリのソート
クエリ中のソート
Sort sort = Sort.by(Sort.Direction.DESC, “id”);
@Autowired
private StudentRepository studentRepository;
@GetMapping("/findByNameOrder")
public List<Student> findByNameOrder() {
// 排序顺序、排序字段
Sort sort = Sort.by(Sort.Direction.DESC, "id");
Iterable<Student> dataList = studentRepository.findAll(sort);
List<Student> resultList = new ArrayList<>();
for (Student student : dataList) {
resultList.add(student);
}
return resultList;
}
6.5 ページングのソート
Pageable に並べ替えが追加されたため、ページ分割して並べ替えることができます。
@Autowired
private StudentRepository studentRepository;
@GetMapping("/findByNamePageOrder")
public List<Student> findByNamePageOrder() {
Sort sort = Sort.by(Sort.Direction.ASC, "id");
// 传参 start、limit、sort规则
// 即可实现 分页 + 排序
Pageable pageable = PageRequest.of(0,2, sort);
Page<Student> page = studentRepository.findAll(pageable);
return page.getContent();
}