Elasticsearch 下载安装及使用总结

十念  金牌会员 | 2024-11-17 12:25:41 | 显示全部楼层 | 阅读模式
打印 上一主题 下一主题

主题 875|帖子 875|积分 2625

官网文档地点:Elasticsearch Guide [8.13]
官网下载地点:Download Elasticsearch
1. 下载安装

1、下载对应体系的版本
这里下载的 Elasticsearch 版本为 8.13.2,Elasticsearch 依赖 Java,因此要先在服务器上安装 JDK,不过高版本的 Elasticsearch 已经内置了 JDK

2、上传到服务器上,解压
  1. tar -xzf elasticsearch-8.13.2-linux-x86_64.tar.gz
复制代码
3、创建新用户
Elasticsearch 不能在 root 用户下启动,因此需要创建一个新用户或者使用其他非 root 用户来启动,将 Elasticsearch 实行目录的所属更改为该用户
  1. groupadd es && useradd es -g es
  2. chown -R es:es elasticsearch-8.13.2
复制代码
4、修改内存巨细
默认分配的内存巨细为 4G,服务器内存不敷可以手动调整分配内存巨细,修改 /config/jvm.options 文件

5、修改 /config/elasticsearch.yml 设置文件
   

  • cluster.name:集群名称,集群下全部节点保持一致
  • node.name:节点名称
  • path.data:数据目录,一样平常可默认,在实行目录下
  • path.logs:日志目录,一样平常可默认,在实行目录下
  • network.host:服务器地点,有几个特殊的预设值,详细可见 Networking | Elasticsearch Guide [8.13],默认为 192.168.0.1
  • http.port:端口,默认 9200
  • discovery.seed_hosts:服务发现种子主机,用于设置集群中其他节点
  • cluster.initial_master_nodes:初始主节点
  6、修改最大内存限制,修改 /etc/sysctl.conf 文件,这里的值为 Elasticsearch 要求的最小值
  1. vm.max_map_count = 262144
复制代码
加载设置
  1. sysctl -p
复制代码
7、使用非 root 用户启动 Elasticsearch,-d 表现背景启动
  1. ./bin/elasticsearch -d
复制代码
一样平常默认会开启安全设置,会自动生成证书文件并在设置文件里自动添加相关设置

8、测试,访问 https://ip:9200,输入用户名密码,在启动时会输出到控制台或者去日志文件检察
  1. Password for the elastic user (reset with `bin/elasticsearch-reset-password -u elastic`):
  2.   r3m5YCt8V=OyGourmPYv
复制代码
或者直接实行 bin/elasticsearch-reset-password -u elastic 生成一个新密码,获取到如下信息即表现乐成

上面默认开启了 ssl,也就是 https 访问,在使用 Java 毗连时默认会去验证证书相关,可以将 xpack.security.http.ssl.enable 设置为 false,使用 http 访问
2. 使用

需要带上用户名密码

1、直接检察服务状态
  1. GET https://ip:9200
复制代码

2、测试分词
  1. POST https://ip:9200/_analyze
复制代码
  

  • tokenizer:选择使用的分词器
  • char_filter:过滤
  • text:需要分词的文本
  

内置分词器
分词器描述分词对象结果standard标准分析器是默认的分析器,假如没有指定,则使用该分析器。它提供了基于文法的标记化(基于 Unicode 文本分割算法,如 Unicode 标准附件 # 29 所规定) ,并且对大多数语言都有用。The 2 QUICK Brown-Foxes jumped over the lazy dog’s bone.[ the, 2, quick, brown, foxes, jumped, over, the, lazy, dog’s, bone ]simple简单分析器将文本分解为任何非字母字符的标记,如数字、空格、连字符和撇号、放弃非字母字符,并将大写字母更改为小写字母。The 2 QUICK Brown-Foxes jumped over the lazy dog’s bone.[ the, quick, brown, foxes, jumped, over, the, lazy, dog, s, bone ]whitespace空格分析器在碰到空白字符时将文本分解为术语The 2 QUICK Brown-Foxes jumped over the lazy dog’s bone.[ The, 2, QUICK, Brown-Foxes, jumped, over, the, lazy, dog’s, bone. ]stop停止分析器与简单分析器相同,但增长了删除停止字的支持。默认使用的是_english_ 停止词。The 2 QUICK Brown-Foxes jumped over the lazy dog’s bone.[ quick, brown, foxes, jumped, over, lazy, dog, s, bone ]keyword不分词,把整个字段当做一个整体返回The 2 QUICK Brown-Foxes jumped over the lazy dog’s bone.[The 2 QUICK Brown-Foxes jumped over the lazy dog’s bone.]pattern模式分析器使用正则表达式将文本拆分为术语。正则表达式应该匹配令牌分隔符,而不是令牌本身。正则表达式默认为w+ (或全部非单词字符)。The 2 QUICK Brown-Foxes jumped over the lazy dog’s bone.[ the, 2, quick, brown, foxes, jumped, over, the, lazy, dog, s, bone ] 扩展,中文分词器
分词器描述分词对象结果ik_smartik 分词器中的简单分词器,支持自界说字典,远程字典学如逆水行舟,不进则退[学如逆水行舟,不进则退]ik_max_wordik_分词器的全量分词器,支持自界说字典,远程字典学如逆水行舟,不进则退[学如逆水行舟,学如逆水,逆水行舟,逆水,行舟,不进则退,不进,则,退] 下载地点:Releases · infinilabs/analysis-ik (github.com)
上传到服务器上 /plugins/ik 目录下,解压
  1. unzip elasticsearch-analysis-ik-8.12.2.zip
复制代码
注意要设置 ik 分词器的 Elasticsearch 版本,修改 /plugins/ik/plugin-descriptor.properties 文件,然后重启服务

1.2.1 索引

相当于数据库表
1、创建索引,indexs 为对应的索引名称
  1. POST https://ip:9200/indexs
复制代码

重复创建的话会报错

创建索引时可以指定 mapping,给字段设置类型和分词器等

2、查询索引,indexs 为对应的索引名称
  1. GET https://ip:9200
  2. /indexs
复制代码
这里没有 mapping,在文档写入 Elasticsearch 时,会根据文档字段自动辨认类型,这种机制称之为动态映射

3、删除索引,indexs 为对应的索引名称
  1. DELETE https://ip:9200/indexs
复制代码

1.2.2 文档

1、添加文档,indexs 为对应的索引名称
  1. POST https://ip:9200/indexs
  2. /_doc         # 使用体系生成idPOST https://ip:9200/indexs
  3. /_create/1    # 使用指定idPOST https://ip:9200/indexs
  4. /_doc/1       # 使用指定id,不存在创建,存在更新
复制代码

再检察索引可以发现已经有了 mapping

2、查询文档,indexs 为对应的索引名称
  1. GET https://ip:9200
  2. /indexs/_doc/1  # 查询单个文档GET http://ip:9200/indexs/_search  # 查询全部文档
复制代码


条件查询
  1. GET http://ip:9200/indexs/_search?q=content:test   # q=查询属性名:查询属性值
复制代码

3、删除文档,indexs 为对应的索引名称
  1. DELETE http://ip:9200/indexs/_doc/1
复制代码

4、修改文档,indexs 为对应的索引名称
全量更新,相当于删除了原来的文档然后重新添加
  1. PUT http://ip:9200/indexs/_doc/1
复制代码

部门更新,不对原始文档进行更新,而是对原始文档对象中的 doc 属性中的指定属性更新
  1. POST http://ip:9200/indexs/_update/1
复制代码

3. 整合 Java

有以下几种通过 Java 操作 Elasticsearch 的方式


  • ElasticsearchRepository:雷同 MyBatis-Plus 的操作
  • ElasticsearchTemplate/ElasticSearchRestTemplate:雷同 Redistemplate 的操作
  • RestHighLevelClient:Elasticsearch 官方提供的 Java 客户端,使用 DSL 的格式来操作,新版本已被弃用
  • Elasticsearch Java API Client:替换 RestHighLevelClient
3.1 ElasticsearchRepository

3.1.1 引入依赖

  1. <dependencies>
  2.         <dependency>
  3.             <groupId>org.springframework.boot</groupId>
  4.             <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
  5.         </dependency>
  6.         <dependency>
  7.             <groupId>org.springframework.boot</groupId>
  8.             <artifactId>spring-boot-starter-web</artifactId>
  9.         </dependency>
  10.         <dependency>
  11.             <groupId>org.projectlombok</groupId>
  12.             <artifactId>lombok</artifactId>
  13.         </dependency>
  14. </dependencies>
复制代码
3.1.2 设置文件

设置 Elasticsearch 的服务器地点以及用户名密码
  1. spring:
  2.   elasticsearch:
  3.     uris: http://127.0.0.1:9200
  4.     username: elastic
  5.     password: elastic
复制代码
3.1.3 文档实体类

  1. import lombok.Data;
  2. import org.springframework.data.annotation.Id;
  3. import org.springframework.data.elasticsearch.annotations.Document;
  4. @Data
  5. @Document(indexName = "articles")
  6. public class Article {
  7.     @Id
  8.     private String id;
  9.     private String title;
  10.     private String content;
  11. }
复制代码
  

  • @Document(indexName = "articles"):指定文档的索引名称
  • @Id:指定该字段作为文档 ID
  3.1.4 数据访问层

继承 ElasticsearchRepository,它提供了一套标准的方法定名规范,符合规范的方法名在输入的时候就会有提示,好比 findByXxx(T xxx),会自动为符合定名规范的方法生成对应的 DSL 语句
  1. import fable.entity.Article;
  2. import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
  3. public interface ArticleRepository extends ElasticsearchRepository<Article, String> {
  4.     Article findByContent(String content);
  5. }
复制代码
3.1.5 Service

  1. import fable.repository.ArticleRepository;
  2. import fable.entity.Article;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.stereotype.Service;
  5. @Service
  6. public class ArticleService {
  7.     private final ArticleRepository articleRepository;
  8.     @Autowired
  9.     public ArticleService(ArticleRepository articleRepository) {
  10.         this.articleRepository = articleRepository;
  11.     }
  12.     public Article findByContent() {
  13.         return articleRepository.findByContent("test");
  14.     }
  15.     public void save() {
  16.         Article article = new Article();
  17.         article.setId("test");
  18.         article.setTitle("test");
  19.         article.setContent("test save");
  20.         articleRepository.save(article);
  21.     }
  22. }
复制代码
3.1.6 Controller

  1. import fable.entity.Article;
  2. import fable.service.ArticleService;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.web.bind.annotation.GetMapping;
  5. import org.springframework.web.bind.annotation.RestController;
  6. @RestController
  7. public class ArticleController {
  8.     private final ArticleService articleService;
  9.     @Autowired
  10.     public ArticleController(ArticleService articleService) {
  11.         this.articleService = articleService;
  12.     }
  13.     @GetMapping("/findByContent")
  14.     public Article findByContent() {
  15.         return articleService.findByContent();
  16.     }
  17.     @GetMapping("/save")
  18.     public void save() {
  19.         articleService.save();
  20.     }
  21. }
复制代码
3.1.7 启动类

添加 @EnableElasticsearchRepositories 注解,设置包扫描
  1. import org.springframework.boot.SpringApplication;
  2. import org.springframework.boot.autoconfigure.SpringBootApplication;
  3. import org.springframework.data.elasticsearch.repository.config.EnableElasticsearchRepositories;
  4. @SpringBootApplication
  5. @EnableElasticsearchRepositories(basePackages = "fable.repository")
  6. public class FableApplication {
  7.     public static void main(String[] args) {
  8.         SpringApplication.run(FableApplication.class, args);
  9.     }
  10. }
复制代码
3.1.8 测试

访问 /save 接口,可以看到文档信息已经添加了进来

访问 /findByContent 接口,可以看到对应的文档信息

3.2 ElasticsearchTemplate/ElasticSearchRestTemplate

将 ElasticsearchTemplate/ElasticSearchRestTemplate 注入进来然后使用对应的方法即可,可自行相识
  1. @Service
  2. public class ArticleService {
  3.     private final ArticleRepository articleRepository;
  4.     private final ElasticsearchTemplate elasticsearchTemplate;
  5.     @Autowired
  6.     public ArticleService(ArticleRepository articleRepository, ElasticsearchTemplate elasticsearchTemplate) {
  7.         this.articleRepository = articleRepository;
  8.         this.elasticsearchTemplate = elasticsearchTemplate;
  9.     }
  10. }
复制代码
3.3 RestHighLevelClient

3.3.1 引入依赖

  1. <dependencies>
  2.         <dependency>
  3.             <groupId>org.springframework.boot</groupId>
  4.             <artifactId>spring-boot-starter-web</artifactId>
  5.         </dependency>
  6.         <dependency>
  7.             <groupId>org.elasticsearch.client</groupId>
  8.             <artifactId>elasticsearch-rest-high-level-client</artifactId>
  9.         </dependency>
  10. </dependencies>
复制代码
3.3.2 Controller

  1. import org.apache.http.HttpHost;
  2. import org.apache.http.auth.AuthScope;
  3. import org.apache.http.auth.UsernamePasswordCredentials;
  4. import org.apache.http.impl.client.BasicCredentialsProvider;
  5. import org.elasticsearch.action.get.GetRequest;
  6. import org.elasticsearch.action.get.GetResponse;
  7. import org.elasticsearch.client.RequestOptions;
  8. import org.elasticsearch.client.RestClient;
  9. import org.elasticsearch.client.RestClientBuilder;
  10. import org.elasticsearch.client.RestHighLevelClient;
  11. import org.springframework.web.bind.annotation.GetMapping;
  12. import org.springframework.web.bind.annotation.RestController;
  13. import java.io.IOException;
  14. @RestController
  15. public class ArticleController {
  16.     @GetMapping("/get")
  17.     public GetResponse get() throws IOException {
  18.         BasicCredentialsProvider provider = new BasicCredentialsProvider();
  19.         provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "elastic"));
  20.         RestClientBuilder builder = RestClient.builder(new HttpHost("127.0.0.1", 9200, "http"))
  21.                 .setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder.setDefaultCredentialsProvider(provider));
  22.         RestHighLevelClient client = new RestHighLevelClient(builder);
  23.         GetRequest getRequest = new GetRequest("articles", "test");
  24.         return client.get(getRequest, RequestOptions.DEFAULT);
  25.     }
  26. }
复制代码
3.3.3 测试

访问 /get 接口,可以看到对应的文档信息

3.4 Elasticsearch Java API Client

3.4.1 引入依赖

  1. <dependencies>
  2.         <dependency>
  3.             <groupId>org.springframework.boot</groupId>
  4.             <artifactId>spring-boot-starter-web</artifactId>
  5.         </dependency>
  6.         <dependency>
  7.             <groupId>co.elastic.clients</groupId>
  8.             <artifactId>elasticsearch-java</artifactId>
  9.         </dependency>
  10.         <dependency>
  11.             <groupId>org.projectlombok</groupId>
  12.             <artifactId>lombok</artifactId>
  13.         </dependency>
  14. </dependencies>
复制代码
3.4.2 文档实体类

  1. import lombok.Data;
  2. @Data
  3. public class Article {
  4.     private String id;
  5.     private String title;
  6.     private String content;
  7. }
复制代码
3.4.3 Controller

需要注意这里的文档实体类必须包含索引的全部字段,否则会报错无法解析
  1. import co.elastic.clients.elasticsearch.ElasticsearchClient;
  2. import co.elastic.clients.elasticsearch.core.GetResponse;
  3. import co.elastic.clients.json.jackson.JacksonJsonpMapper;
  4. import co.elastic.clients.transport.ElasticsearchTransport;
  5. import co.elastic.clients.transport.rest_client.RestClientTransport;
  6. import fable.entity.Article;
  7. import org.apache.http.HttpHost;
  8. import org.apache.http.auth.AuthScope;
  9. import org.apache.http.auth.UsernamePasswordCredentials;
  10. import org.apache.http.impl.client.BasicCredentialsProvider;
  11. import org.elasticsearch.client.RestClient;
  12. import org.springframework.web.bind.annotation.GetMapping;
  13. import org.springframework.web.bind.annotation.RestController;
  14. import java.io.IOException;
  15. @RestController
  16. public class ArticleController {
  17.     @GetMapping("/get")
  18.     public Article get() throws IOException {
  19.         BasicCredentialsProvider provider = new BasicCredentialsProvider();
  20.         provider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("elastic", "UnF8lyv82vJarD=iAbcZ"));
  21.         RestClient restClient = RestClient.builder(new HttpHost("124.222.118.90", 9200, "http"))
  22.                 .setHttpClientConfigCallback(httpAsyncClientBuilder -> httpAsyncClientBuilder.setDefaultCredentialsProvider(provider))
  23.                 .build();
  24.         ElasticsearchTransport transport = new RestClientTransport(
  25.                 restClient, new JacksonJsonpMapper()
  26.         );
  27.         ElasticsearchClient elasticsearchClient = new ElasticsearchClient(transport);
  28.         GetResponse<Article> response = elasticsearchClient.get(builder -> builder.index("articles").id("test"), Article.class);
  29.         System.out.println(response);
  30.         return response.source();
  31.     }
  32. }
复制代码
3.4.4 测试

访问 /get 接口,可以看到文档信息如下


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

十念

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表