Java连接ES
创建Maven工程
导入依赖
<dependencies>
<!-- 1. elasticsearch-->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>6.5.4</version>
</dependency>
<!-- 2. elasticsearch的高级API-->
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.5.4</version>
</dependency>
<!-- 3. junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!-- 4. lombok-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.16.22</version>
</dependency>
</dependencies>
创建测试类,连接ES
public class ESClient {
public static RestHighLevelClient getClient(){
// 创建HttpHost对象
HttpHost httpHost = new HttpHost("192.168.199.109",9200);
// 创建RestClientBuilder
RestClientBuilder clientBuilder = RestClient.builder(httpHost);
// 创建RestHighLevelClient
RestHighLevelClient client = new RestHighLevelClient(clientBuilder);
// 返回
return client;
}
}
Java操作索引
创建索引
代码如下
public class Demo2 {
RestHighLevelClient client = ESClient.getClient();
String index = "person";
String type = "man";
@Test
public void createIndex() throws IOException {
//1. 准备关于索引的settings
Settings.Builder settings = Settings.builder()
.put("number_of_shards", 3)
.put("number_of_replicas", 1);
//2. 准备关于索引的结构mappings
XContentBuilder mappings = JsonXContent.contentBuilder()
.startObject()
.startObject("properties")
.startObject("name")
.field("type","text")
.endObject()
.startObject("age")
.field("type","integer")
.endObject()
.startObject("birthday")
.field("type","date")
.field("format","yyyy-MM-dd")
.endObject()
.endObject()
.endObject();
//3. 将settings和mappings封装到一个Request对象
CreateIndexRequest request = new CreateIndexRequest(index)
.settings(settings)
.mapping(type,mappings);
//4. 通过client对象去连接ES并执行创建索引
CreateIndexResponse resp = client.indices().create(request, RequestOptions.DEFAULT);
//5. 输出
System.out.println("resp:" + resp.toString());
}
}
检查索引是否存在
代码如下
@Test
public void exists() throws IOException {
//1. 准备request对象
GetIndexRequest request = new GetIndexRequest();
request.indices(index);
//2. 通过client去操作
boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
//3. 输出
System.out.println(exists);
}
删除索引
代码如下
@Test
public void delete() throws IOException {
//1. 准备request对象
DeleteIndexRequest request = new DeleteIndexRequest();
request.indices(index);
//2. 通过client对象执行
AcknowledgedResponse delete = client.indices().delete(request, RequestOptions.DEFAULT);
//3. 获取返回结果
System.out.println(delete.isAcknowledged());
}
Java操作文档
添加文档操作
代码如下
public class Demo3 {
ObjectMapper mapper = new ObjectMapper();
RestHighLevelClient client = ESClient.getClient();
String index = "person";
String type = "man";
@Test
public void createDoc() throws IOException {
//1. 准备一个json数据
Person person = new Person(1,"张三",23,new Date());
String json = mapper.writeValueAsString(person);
//2. 准备一个request对象(手动指定id)
IndexRequest request = new IndexRequest(index,type,person.getId().toString());
request.source(json, XContentType.JSON);
//3. 通过client对象执行添加
IndexResponse resp = client.index(request, RequestOptions.DEFAULT);
//4. 输出返回结果
System.out.println(resp.getResult().toString());
}
}
修改文档
代码如下
@Test
public void updateDoc() throws IOException {
//1. 创建一个Map,指定需要修改的内容
Map<String,Object> doc = new HashMap<>();
doc.put("name","张大三");
String docId = "1";
//2. 创建request对象,封装数据
UpdateRequest request = new UpdateRequest(index,type,docId);
request.doc(doc);
//3. 通过client对象执行
UpdateResponse update = client.update(request, RequestOptions.DEFAULT);
//4. 输出返回结果
System.out.println(update.getResult().toString());
}
删除文档
代码如下
@Test
public void deleteDoc() throws IOException {
//1. 封装Request对象
DeleteRequest request = new DeleteRequest(index,type,"1");
//2. client执行
DeleteResponse resp = client.delete(request, RequestOptions.DEFAULT);
//3. 输出结果
System.out.println(resp.getResult().toString());
}
Java批量操作文档
批量添加
代码如下
@Test
public void bulkCreateDoc() throws IOException {
//1. 准备多个json数据
Person p1 = new Person(1,"张三",23,new Date());
Person p2 = new Person(2,"李四",24,new Date());
Person p3 = new Person(3,"王五",25,new Date());
String json1 = mapper.writeValueAsString(p1);
String json2 = mapper.writeValueAsString(p2);
String json3 = mapper.writeValueAsString(p3);
//2. 创建Request,将准备好的数据封装进去
BulkRequest request = new BulkRequest();
request.add(new IndexRequest(index,type,p1.getId().toString()).source(json1,XContentType.JSON));
request.add(new IndexRequest(index,type,p2.getId().toString()).source(json2,XContentType.JSON));
request.add(new IndexRequest(index,type,p3.getId().toString()).source(json3,XContentType.JSON));
//3. 用client执行
BulkResponse resp = client.bulk(request, RequestOptions.DEFAULT);
//4. 输出结果
System.out.println(resp.toString());
}
批量删除
代码如下
@Test
public void bulkDeleteDoc() throws IOException {
//1. 封装Request对象
BulkRequest request = new BulkRequest();
request.add(new DeleteRequest(index,type,"1"));
request.add(new DeleteRequest(index,type,"2"));
request.add(new DeleteRequest(index,type,"3"));
//2. client执行
BulkResponse resp = client.bulk(request, RequestOptions.DEFAULT);
//3. 输出
System.out.println(resp);
}
ElasticSearch的各种查询
term&terms查询
term查询
term的查询是代表完全匹配,搜索之前不会对你搜索的关键字进行分词,对你的关键字去文档分词库中去匹配内容。
# term查询
POST /sms-logs-index/sms-logs-type/_search
{
"from": 0, # limit ?
"size": 5, # limit x,?
"query": {
"term": {
"province": {
"value": "北京"
}
}
}
}
代码实现方式
// Java代码实现方式
@Test
public void termQuery() throws IOException {
//1. 创建Request对象
SearchRequest request = new SearchRequest(index);
request.types(type);
//2. 指定查询条件
SearchSourceBuilder builder = new SearchSourceBuilder();
builder.from(0);
builder.size(5);
builder.query(QueryBuilders.termQuery("province","北京"));
request.source(builder);
//3. 执行查询
SearchResponse resp = client.search(request, RequestOptions.DEFAULT);
//4. 获取到_source中的数据,并展示
for (SearchHit hit : resp.getHits().getHits()) {
Map<String, Object> result = hit.g