elasticSearch集群搭建---入门篇二
Posted phl成为自己的太阳
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了elasticSearch集群搭建---入门篇二相关的知识,希望对你有一定的参考价值。
Elasticsearch(二)
1 通过java客户端对es维护
1.1 工程搭建
- 创建maven工程
- 添加依赖,在pom.xml文件添加如下依赖:
<dependencies>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.6.8</version>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.6.8</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-to-slf4j</artifactId>
<version>2.9.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.24</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.21</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
- 创建测试类ElasticSearchDemo
1.2 索引操作
1.2.1 创建索引
在测试类中添加testCreateIndex方法:
为方便测试:在测试类中添加before和after方法,分别在测试方法前执行,创建客户端连接对象,测试方法执行后执行,关闭资源
private Client client = null;
@Before
public void before() {
client = new PreBuiltTransportClient(Settings.EMPTY)
.addTransportAddress(new InetSocketTransportAddress(
new InetSocketAddress("localhost", 9300)));
}
@After
public void after() {
client.close();
}
// 创建索引
@Test
public void testCreateIndex() {
client.admin().indices().prepareCreate("blog3").get();
}
1.2.2 删除索引
在测试类中添加testDeleteIndex方法:
//删除索引
@Test
public void testDeleteIndex() {
client.admin().indices().prepareDelete("blog3").get();
}
1.3 创建映射
1.3.1 创建映射前
这里的映射表示创建索引类型结构,如果不创建映射,Elasticsearch会默认根据创建的文档中的数据用来创建映射。查看之前的blog3的映射。
1.3.2 创建映射
在测试类中添加方法:
// 创建映射 注意创建映射时一定要有索引的存在,不然无法创建映射,
// 映射就相当于表结构 创建表和表的结构时,必须要有数据库(索引)
@Test
public void testCreateMapping1() throws Exception {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder();
xContentBuilder
.startObject()
.startObject("properties")
.startObject("id")
.field("type", "long")
.endObject()
.startObject("title")
.field("type", "text")
.field("store", false)
.field("analyzer", "ik_smart")
.endObject()
.startObject("content")
.field("type", "text")
.field("store", false)
.field("analyzer", "ik_smart")
.endObject()
.endObject()
.endObject();
PutMappingRequest mappingRequest = Requests.putMappingRequest("blog3").type("article").source(xContentBuilder);
client.admin().indices().putMapping(mappingRequest);
}
1.3.3 创建映射后
创建映射后的结果如下:
1.4 文档数据操作
1.4.1 创建文档数据
1.4.1.1 通过XContentBuilder创建
通过XContentBuilder构建文档数据。在测试中添加方法:
// 创建文档数据
@Test
public void testCreateDocByXContentBuilder() throws IOException {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder()
.startObject()
.field("id", 2)
.field("title", "学习路线")
.field("content", "计算机组成原理、计算机网络、数据结构、操作系统等")
.endObject();
client.prepareIndex("blog3","article","2").setSource(xContentBuilder).get();
}
1.4.1.2 通过POJO创建
通过POJO构建文档数据。在测试中添加方法:
-
添加Jackson依赖(需要将pojo转成json对象)
<!--jackson JSON转换包--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.8.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.8.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.8.1</version> </dependency>
-
创建pojo,在src目录下创建Article对象
package com.demo;
public class Article {
private Integer id;
private String title;
private String content;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
return "Article{" +
"id=" + id +
", title='" + title + '\\'' +
", content='" + content + '\\'' +
'}';
}
}
- 编写代码
//根据bean创建文档数据
@Test
public void testCreateDocByPojo() throws IOException {
Article article = new Article();
article.setId(3);
article.setTitle("elasticSearch");
article.setContent("elasticSearch时搜索引擎服务,查询速度快");
ObjectMapper objectMapper = new ObjectMapper();
byte[] source = objectMapper.writeValueAsBytes(article);
client.prepareIndex("blog3","article","3").setSource(source).get();
}
1.4.2 更新文档数据
1.4.2.1 通过prepareUpdate方法修改
在测试类添加方法:
//根据prepareUpdate更新文档数据
@Test
public void testUpdateDoc() throws JsonProcessingException {
Article article = new Article();
article.setId(2);
article.setTitle("java学习路线-更新了");
article.setContent("需要学习数据结构、计算机网络、计算机组成原理、操作系统等-更新了");
ObjectMapper objectMapper = new ObjectMapper();
byte[] sources = objectMapper.writeValueAsBytes(article);
client.prepareUpdate("blog3","article","2").setDoc(sources, XContentType.JSON).get();
}
1.4.2.2 通过update方法修改
添加测试方法:
//根据update更新文档数据
@Test
public void testUpdate() throws JsonProcessingException, ExecutionException, InterruptedException {
Article article = new Article();
article.setId(3);
article.setTitle("elasticSearch--更新了");
article.setContent("elasticSearch时搜索引擎服务,查询速度快--更新了");
ObjectMapper objectMapper = new ObjectMapper();
byte[] bytes = objectMapper.writeValueAsBytes(article);
UpdateRequest request = new UpdateRequest("blog3", "article", "3").doc(bytes,XContentType.JSON);
client.update(request).get();
}
1.4.3 删除文档数据
在测试类中添加方法:
//删除文档
@Test
public void testDelte(){
client.prepareDelete("blog3","article","3").get();
}
1.4.4 批量增加数据
在测试类中添加方法:
//批量增加数据
@Test
public void testBatchDocs() throws JsonProcessingException, ExecutionException, InterruptedException {
BulkRequestBuilder bulk = client.prepareBulk();
ObjectMapper objectMapper = new ObjectMapper();
for (int i = 1; i <= 10; i++) {
Article article = new Article();
article.setId(i);
article.setTitle("如何学好es"+i);
article.setContent("理解Elasticsearch需要掌握倒排索引,版本为:"+i);
byte[] bytes = objectMapper.writeValueAsBytes(article);
IndexRequestBuilder indexRequestBuilder = client.prepareIndex("blog3", "article", String.valueOf(i)).setSource(bytes, XContentType.JSON);
bulk.add(indexRequestBuilder);
}
bulk.execute().get();
}
1.5 查询
1.5.1 根据字符串查询
在测试类中添加方法:
// 根据字符串查询
@Test
public void testQueryByString() throws Exception {
SearchResponse searchResponse = client.prepareSearch("blog3")
.setTypes("article")
.setQuery(QueryBuilders.queryStringQuery("倒排索引"))// 根据字符串查询
.get();
SearchHits hits = searchResponse.getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
}
1.5.2 根据词条查询
在测试类中添加方法:
// 根据词条查询
/*
* IK分词器,在建立索引的时候将英文都变成了小写,这样方便我们在搜索的时候可以实现“不区分大小写”的搜索,
* 因此在编写程序时,因此我们在根据英文单词查询时,需要将大写字母转成小写字母<toLowerCase()方法>
* */
@Test
public void testQueryByTerm() throws Exception {
SearchResponse searchResponse = client.prepareSearch("blog3")
.setTypes("article")
.setQuery(QueryBuilders.termQuery("content","Elasticsearch".toLowerCase()))//根据词条查询
.get();
SearchHits hits = searchResponse.getHits();
for (SearchHit hit : hits) {
System.out.println(hit.getSourceAsString());
}
}
<http://127.0.0.1:9200/_analyze?analyzer=ik_max_word&pretty=true&text=ElasticSearch是一个全文检索的框架>
1.5.3 结果集处理
在上面的查询中,获取到的结果都是json对象,因此我们可以转成pojo。在测试中添加方法:
//结果集处理
@Test
public void testQueryForResult() throws IOException {
SearchResponse searchResponse = client.prepareSearch("blog3")
.setTypes("article")
.setQuery(QueryBuilders.termQuery("content", "Elasticsearch".toLowerCase()))
.get();
SearchHits hits = searchResponse.getHits();
ArrayList<Article> articles = new ArrayList<>();
ObjectMapper objectMapper = new ObjectMapper();
for Elasticsearch入门学习:集群的搭建