Elasticsearch 学习笔记(二)

140 阅读2分钟

这是我参与11月更文挑战的第10天,活动详情查看:2021最后一次更文挑战

前言

本文衔接 Elasticsearch 学习笔记(一)继续学习Elasticsearch 相关知识点

crud

高亮搜索

会在查询结果的执行属性加上高亮的处理

image.png

分析

挖掘出雇员中最受欢迎的兴趣爱好

image.png

删除

简单删除

删除二号员工

image.png

删除所有

POST /megacorp/employee/_delete_by_query
{
    "query": {
        "match_all": {}
    }
}

条件删除

POST /megacorp/employee/_delete_by_query

{
    "query" : {
        "match" : {
            "last_name" : "Smith"
        }
    }
}

修改

POST /megacorp/employee/1/_update
//doc必须的
{
    "doc" : {
     "last_name" : "test update"
   }
}

spring boot整合

jest

导入依赖

<!-- https://mvnrepository.com/artifact/io.searchbox/jest -->
<dependency>
    <groupId>io.searchbox</groupId>
    <artifactId>jest</artifactId>
    <version>5.3.2</version>
</dependency>

创建索引

@Autowired
	JestClient jestClient;

	@Test
	public void createIndex() {

		Employee employee = new Employee("jack","play basketball",15);

		Index build = new Index.Builder(employee)
				               .index("megacorp")
				               .id("2")
				               .type("employee")
				               .build();

		try {
			jestClient.execute(build);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

查询

@Test
	public void search(){

		String searchJson = "{\n" +
				"    \"query\" : {\n" +
				"        \"match\" : {\n" +
				"            \"first_name\" : \"John\"\n" +
				"        }\n" +
				"    }\n" +
				"}";

		Search build = new Search
								.Builder(searchJson)
								.addIndex("megacorp")
								.addType("employee")
								.build();


		try {
			SearchResult execute = jestClient.execute(build);

			System.out.println(execute.getJsonString());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

删除

@Test
	public void delete(){

		Delete build = new Delete
								.Builder("2")
								.index("megacorp")
								.type("employee")
								.build();

		try {
			jestClient.execute(build);
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

spring data elastic search

在进行整合是注意版本的控制

image.png

分片和副本

索引数据集合存在分片中,分片又分主分片和副本分片,但是每个分片中数据都应该是一样的

也就是说es的集群不是主从复制而是全量备份

写入原理

  • 当客户端发起一个请求写入数据,会有一个协调节点处理请求

  • 将写入数据发送给主分片,主分片同时将数据转发给其他副本分片

  • 一个分片在写入数据时,会先将数据写入的内存buffer和translog,es会有定时的任务1s将buffer中的数据写入到磁盘

  • 写入磁盘之前linux 系统都会先写入os cache

  • 只有当数据写入os cache 才能被查询到,所以es写入是准实时的

  • os cach也会间隔一定时间将数据持久化到segment file中

  • segment file文件达到一定量会执行merge合并为一个segment file