ElasticSearch(ES)极速入门

ElasticSearch

官方下载链接

https://www.elastic.co/cn/downloads/past-releases#elasticsearch

什么是ElasticSearch

Elasticsearch和redis\mysql一样,不仅服务于java语言,其它语言也可以使用

它的功能也类似一个数据库,能高效的从大量数据中搜索匹配指定关键字的内容

它也将数据保存在硬盘中

这样的软件有一个名称全文搜索引擎

它本质就是一个java项目,使用它进行数据的增删改查就是访问这个项目的控制器方法(url路径)

ES的底层技术

ES使用了java的一套名为Lucene的API(ElasticSearch封装了Lucene:相当于mybatis封装了JDBC)

这个API提供了全文搜索引擎核心操作的接口,相当于搜索引擎的核心支持,ES是在Lucene的基础上进行了完善,实现了开箱即用的搜索引擎软件

市面上和ES功能类似的软件有

Solr(淘汰了)/MongoDB

为什么需要Elasticsearch

数据库进行模糊查询严重低下(因为模糊查询用不了索引,只能逐个遍历)

所有关系型数据库都有这个缺点(mysql\mariaDB\oracle\DB2等)

在执行类似下面模糊查询时

select * from spu where spu_name like '%鼠标%'

测试证明一张千万级别的数据表进行模糊查询需要20秒以上

当前互联网项目要求"三高"的需求下,这样的效率肯定不能接受

Elasticsearch主要是为了解决数据库模糊查询性能低下问题的

ES进行优化之后,从同样数据量的ES中查询相同条件数据,效率能够提高100倍以上

数据库中的索引(基本概念)

所谓的索引(index)其实就是数据目录

通常情况下,索引是为了提高查询效率的

数据库索引分两大类

  • 聚集索引
  • 非聚集索引

聚集索引就是数据库保存数据的物理顺序依据,默认情况下就是主键id,所以按id查询数据库中的数据效率非常高(ES没有优化空间)

非聚集索引

如果想在非主键列上添加索引,就是非聚集索引了

例如我们在数据库表中存在一个姓名列,我们为姓名列创建索引

在创建索引时,会根据姓名内容来创建索引

例如"张三" 这个姓名,创建索引后查询效率就会明显提升

如果没有索引,这样的查询就会引起效率最低的"逐行搜索",就是一行一行的查这个数据的姓名是不是张三,效率就会非常低

模糊查询时因为’%鼠标%',使用的是前模糊条件,使用索引必须明确前面的内容是什么,前模糊查询是不能使用索引的,只能是全表的逐行搜索,所以效率非常低

所以当我们项目中设计了根据用户输入关键字进行查询时,需要使用全文搜索引擎来优化

索引面试题

1.创建的索引会占用硬盘空间

2.创建索引之后,对该表进行增删改操作时,会引起索引的更新,所以效率会降低

3.对数据库进行批量新增时,先删除索引,增加完毕之后再创建

4.不要对数据样本少的列添加索引

5.模糊查询时,查询条件前模糊的情况,是无法启用索引的

6.每次从数据表中查询的数据的比例越高,索引的效果越低

7.当我们执行查询时,where条件后应该先查询有索引的列

Elasticsearch运行原理

要想使用ES提高模糊查询效率

首先要将数据库中的数据复制到ES中

在新增数据到ES的过程中,ES可以对指定的列进行分词索引保存在索引库中

形成倒排索引结构

	from <= sql
id    			name

1				罗技激光无线游戏鼠标				
2				雷蛇激光无线竞技鼠标
3				罗技高速无线静音鼠标
4				雷蛇游戏红轴无线键盘
	to => ES
索引				ids

罗技      		1 3
激光				1 2
无线				1 2 3 4
游戏				1 4
鼠标				1 2 3
雷蛇				2 4
竞技				2
高速				3
静音				3
红轴				4
键盘				4

Elasticsearch的启动

widows直接打开

elasticsearch.bat

linux:

tar -xvf elasticsearch-7.6.2-linux-x86_64.tar.gz
cd elasticsearch-7.6.2/bin
./elasticsearch

浏览器输入地址:localhost:9200看到如下内容即可

{
  "name" : "LAPTOP-2UO2VJ6R",
  "cluster_name" : "elasticsearch",
  "cluster_uuid" : "o37YXUC0Tf68KPYQyI62RA",
  "version" : {
    "number" : "7.6.2",
    "build_flavor" : "default",
    "build_type" : "zip",
    "build_hash" : "ef48eb35cf30adf4db14086e8aabd07ef6fb113f",
    "build_date" : "2020-03-26T06:34:37.794943Z",
    "build_snapshot" : false,
    "lucene_version" : "8.4.0",
    "minimum_wire_compatibility_version" : "6.8.0",
    "minimum_index_compatibility_version" : "6.0.0-beta1"
  },
  "tagline" : "You Know, for Search"
}

ES基本使用

ik分词插件的使用

ik文件夹放到ES的plugins目录下

实际上除了ik_smart之外还有ik_max_word

POST http://localhost:9200/_analyze
Content-Type: application/json

{
  "text": "北京成功举行了冬季奥林匹克运动会",
  "analyzer": "ik_smart"
}
POST http://localhost:9200/_analyze
Content-Type: application/json

{
  "text": "北京成功举行了冬季奥林匹克运动会",
  "analyzer": "ik_max_word"
}

上面的两个分词器运行分词,结果会有非常明显的区别

总结区别如下

ik_smart

  • 优点:特征是粗略快速的将文字进行分词,占用空间小,查询速度快

  • 缺点:分词的颗粒度大,可能跳过一些重要分词,导致查询结果不全面,查全率低

ik_max_word

  • 优点:特征是详细的文字片段进行分词,查询时查全率高,不容易遗漏数据
  • 缺点:因为分词太过详细,导致有一些无用分词,占用空间较大,查询速度慢

SpringBoot 操作 Elasticsearch

Spring Data简介

原生状态下,我们使用JDBC连接数据库,因为代码过于繁琐,所以改为使用Mybatis框架

在ES的原生状态下,我们java代码需要使用socket访问ES,但是也是过于繁琐,我们可以使用SpringData框架简化

Spring Data是Spring提供的一套连接各种第三方数据源的框架集

我们需要使用的是其中连接ES的Spring Data Elasticseatrch

官方网站:https://spring.io/projects/spring-data

基本配置

pom依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<!--  spring data elasticsearch 依赖   -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<!--  为了方便测试添加测试依赖  -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
</dependency>

yml配置

# 设置ES所在的ip地址端口号
spring:
  elasticsearch:
    rest:
      uris: http://localhost:9200

# SpringDataElasticsearch底层有一个专门输出运行状态的类,也要设置
logging:
  level:
    org.elasticsearch.client.RestClient: debug

和ES关联的实体类

和数据库一样

我们操作ES时也需要一个类似实体类的数据类,作为操作ES的数据载体

search项目创建entity包

在包中创建Item(商品)类

@Data
@Accessors(chain = true)   // 支持链式set赋值功能
@AllArgsConstructor        // 自动生成当前类的全参构造
@NoArgsConstructor         // 自动生成当前类的无参构造
// @Document是SpringDataES框架标记实体类的注解
// indexName指定的是索引名称,运行时items索引不存在,SpringDataES会自动创建这个索引
@Document(indexName = "items")
public class Item implements Serializable {

    // SpringData标记当前属性为ES主键的注解
    @Id
    private Long id;
    // SpringData标记title属性的支持分词的类似和相关分词器
    @Field(type = FieldType.Text,
            analyzer = "ik_max_word",
            searchAnalyzer = "ik_max_word")
    private String title;
    // Keyword是不需要分词的字符串类型
    @Field(type = FieldType.Keyword)
    private String category;
    @Field(type = FieldType.Keyword)
    private String brand;
    @Field(type = FieldType.Double)
    private Double price;
    // 图片地址不会称为搜索条件,所以不需要进行索引,不索引能节省一些数据空间
    // 设置index=false 今后所有不会称为查询条件的列都照此配置
    // 不索引,不代表不保存数据,数据本身仍然是保存在ES的
    @Field(type = FieldType.Keyword,index = false)
    private String imgPath;

    // images/xxx/xxx/a09f-887ac-ac006-7128311231234

}
使用ES操作数据

ES是一个数据库性质的软件

可以执行增删改查操作,只是他操作数据不使用sql,数据的结构和关系型数据库也不同

我们先了解一下ES保存数据的结构

  • ES启动后,ES服务可以创建多个index(索引),index可以理解为数据库中表的概念
  • 一个index可以创建多个保存数据的document(文档),一个document理解为数据库中的一行数据
  • 一个document中可以保存多个属性和属性值,对应数据库中的字段(列)和字段值
ES文档
### 创建 index
PUT http://localhost:9200/questions
### 删除一个Index
DELETE http://localhost:9200/questions
### 设置index中的文档属性采用ik分词
POST http://localhost:9200/questions/_mapping
Content-Type: application/json

{
  "properties": {
    "title": {
      "type": "text",
      "analyzer": "ik_max_word",
      "search_analyzer": "ik_max_word"
    },
    "content": {
      "type": "text",
      "analyzer": "ik_max_word",
      "search_analyzer": "ik_max_word"
    }
  }
}
### questions 中添加文档
POST http://localhost:9200/questions/_create/1
Content-Type: application/json

{
  "id":1,
  "title":"Java基本数据类型有哪些",
  "content":"面时候为啥要问基本类型这么简单问题呀,我们要如何回答呢?"
}
### questions 中添加文档
POST http://localhost:9200/questions/_create/2
Content-Type: application/json

{
  "id":2,
  "title":"int类型的范围",
  "content":"为啥要了解int类型的范围呢?"
}

### questions 中添加文档
POST http://localhost:9200/questions/_create/3
Content-Type: application/json

{
  "id":3,
  "title":"常用集合类有哪些",
  "content":"为啥企业经常问集合呀?该如何回复呢"
}

### questions 中添加文档
POST http://localhost:9200/questions/_create/4
Content-Type: application/json

{
  "id":4,
  "title":"线程的run方法和start方法有啥区别",
  "content":"run方法可以执行线程的计算过程, start也可以执行线程的计算过程,用途一样么?"
}
### 更新questions索引中的文档
POST http://localhost:9200/questions/_doc/4/_update
Content-Type: application/json

{
  "doc": {
    "title": "Java线程的run方法和start方法有啥区别"
  }
}
### 删除questions中的一个文档
DELETE http://localhost:9200/questions/_doc/2
### 查询数据
GET http://localhost:9200/questions/_doc/4
### 搜索 ES
POST http://localhost:9200/questions/_search
Content-Type: application/json

{
  "query": { "match": {"title": "类型" } }
}
### 多字段搜索
POST http://localhost:9200/questions/_search
Content-Type: application/json

{
  "query": {
    "bool": {
      "should": [
        { "match": { "title":  "java类型" }},
        { "match": { "content": "java类型"}}
      ]
    }
  }
}
创建操作ES的持久层
// Repository 是spring家族框架对持久层的命名
@Repository
public interface ItemRepository extends
                                ElasticsearchRepository<Item,Long>  {
    // ItemRepository接口要继承SpringData提供的ElasticsearchRepository父接口
    // 一旦继承,当前接口就会被识别为连接ES的持久层类,SpringData会自动为它生成基本增删改查方法
    // ElasticsearchRepository<[关联的实体类名称],[实体类主键类型]>

    // SpringData自定义查询
    // 可以通过遵循SpringData框架给定的格式定义方法名称,
    // SpringData会根据方法名称自动生成查询语句
    // query(查询):表示当前方法是一个查询方法,类似sql语句中的select
    // Item/Items:确定要查询哪一个实体类,不带s的是单个对象,带s是集合
    // By(通过/根据):标识开始设置查询条件,类似sql语句中的where
    // Title:要查询的字段,可以根据查询条件修改为Item中的任何字段
    // Matches:执行查询的操作,Matches表示字符串的匹配,而且这个匹配是支持分词的,类似sql语句的like
    Iterable<Item> queryItemsByTitleMatches(String title);


    // 多条件查询
    // 多个条件之间我们需要使用And和Or来分隔,来表示他们的查询逻辑
    // 方法的参数赋值是依据方法定义的参数顺序依次向条件中赋值的
    Iterable<Item> queryItemsByTitleMatchesAndBrandMatches(
                                    String title,String brand);

    // 排序查询
    Iterable<Item> queryItemsByTitleMatchesOrBrandMatchesOrderByPriceDesc(
            String title,String brand);

    // 分页查询
    // 返回值修改为Page类型,这个类型中包含了查询到的分页数据,和本次查询相关的分页信息
    // 分页信息包含:当前页,总页数,总条数,每页条数,是否有上一页或下一页等
    // 方法参数,在所有的参数后再添加一个新的参数类型,Pageable

    Page<Item> queryItemsByTitleMatchesOrBrandMatchesOrderByPriceDesc(
            String title, String brand, Pageable pageable);


}
测试ES
// 装配ItemRepository
@Autowired
private ItemRepository itemRepository;

// 执行单增
@Test
void addOne(){
    // 实例化一个Item对并赋值
    Item item=new Item()
        .setId(1L)
        .setTitle("罗技激光无线游戏鼠标")
        .setCategory("鼠标")
        .setBrand("罗技")
        .setPrice(168.0)
        .setImgPath("/1.jpg");
    // 利用SpringDataES提供的方法完成新增功能
    itemRepository.save(item);
    System.out.println("ok");
}
// 单查
@Test
void getOne(){
    // SpringDataES提供了按id查询ES中数据的方法
    // Optional是一个类似包装类的概念,查询结果封装到这个类型中
    Optional<Item> optional=itemRepository.findById(1L);
    Item item=optional.get();
    System.out.println(item);
}

// 批量增
@Test
void addList(){
    // 实例化一个List对象
    List<Item> list=new ArrayList<>();
    // 将要新增的对象保存在List中
    list.add(new Item(2L,"罗技激光有线办公鼠标","鼠标",
                      "罗技",88.0,"/2.jpg"));
    list.add(new Item(3L,"雷蛇机械无线游戏键盘","键盘",
                      "雷蛇",299.0,"/3.jpg"));
    list.add(new Item(4L,"微软有线静音办公鼠标","鼠标",
                      "微软",205.0,"/4.jpg"));
    list.add(new Item(5L,"罗技机械有线背光键盘","键盘",
                      "罗技",268.0,"/5.jpg"));
    itemRepository.saveAll(list);
    System.out.println("ok list");
}
// 全查
@Test
void getAll(){
    // SpringDataES对ES全查(指定索引)返回数据的方法
    Iterable<Item> items=itemRepository.findAll();
    for(Item item : items){
        System.out.println(item);
    }
    items.forEach(item -> System.out.println(item));

}

//单条件查询
@Test
void queryOne(){
    // 查询ES中items索引中,title字段包含"游戏"关键字的数据
    Iterable<Item> items=itemRepository.queryItemsByTitleMatches("激光游戏");
    items.forEach(item -> System.out.println(item));
}

// 多条件查询
@Test
void queryTwo(){
    // 查询ES中items索引中,title字段包含"游戏"并且品牌是"罗技"的数据
    Iterable<Item> items=itemRepository
        .queryItemsByTitleMatchesAndBrandMatches("游戏","罗技");
    items.forEach(item -> System.out.println(item));
}


// 排序查询
@Test
void queryOrder(){
    Iterable<Item> items=itemRepository
        .queryItemsByTitleMatchesOrBrandMatchesOrderByPriceDesc(
        "游戏","罗技");
    items.forEach(item -> System.out.println(item));
}

// 分页查询
@Test
void queryPage(){
    int pageNum=2;   // 要查询的页码
    int pageSize=2;  // 每页包含的数据条数
    Page<Item> page=itemRepository
        .queryItemsByTitleMatchesOrBrandMatchesOrderByPriceDesc(
        "游戏","罗技", PageRequest.of(pageNum-1,pageSize));
    page.forEach(item -> System.out.println(item));
    // page对象中包含的分页和信息:
    System.out.println("总页数:"+page.getTotalPages());
    System.out.println("总条数:"+page.getTotalElements());
    System.out.println("当前页:"+(page.getNumber()+1));
    System.out.println("每页条数:"+page.getSize());
    System.out.println("是否为首页:"+page.isFirst());
    System.out.println("是否为末页:"+page.isLast());
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值