1、首先需要下载ES版本与使用的spingboot版本对应的,依赖对应的ES版本号
SpringBoot整合Elasticsearch
在使用SpringBoot整合Elasticsearch 之前,我们应该了解下它们之间对应版本的关系。
Spring Boot Version (x) | Spring Data Elasticsearch Version (y) | Elasticsearch Version (z) |
x <= 1.3.5 | y <= 1.3.4 | z <= 1.7.2* |
x >= 1.4.x | 2.0.0 <=y < 5.0.0** | 2.0.0 <= z < 5.0.0** |
2、本篇文章下载的ES版本为2.0.0:
使用的springboot version为2.0.1:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
</parent>
使用的Spring Data Elasticsearch Version为2.0.4:
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
使用的Elasticsearch Version为2.4.0:
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.4.0</version>
</dependency>
3、首先下载ES2.0.0,之后解压,修改config/elasticsearch.yml文件的集群名称,以及host地址,设置为0.0.0.0,其他机器也可以访问,如果是集群(三个节点),需要将每个机器乳房host配置为单个节点信息,集群名称保持一致,设置node-name.
4、启动ES。选择bin目录下,
,双击bat,启动ES,启动成功如下窗口:
5、访问http://127.0.0.1:9200显示如下信息,则启动成功:
注:http请求交互ES,使用9200端口,Java与ES交互使用9300端口,下面java代码会使用9300
6、开始使用Java操作ES搜索引擎。(必须先执行创建index(prepareIndex())的方法,才能后续的查,改增操作)
1>加上ES依赖:
<!--ES 必须加上-org.apache.logging.log4j ,不然会报类找不到异常-->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.4.0</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>22.0</version>
</dependency>
2>连接ES,创建ES工具类
package com.liu.web.ES;
import com.alibaba.fastjson.JSON;
import com.google.common.net.InetAddresses;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
//import org.elasticsearch.transport.client.PreBuiltTransportClient;
import java.util.HashMap;
import java.util.Map;
public class ESClient {
TransportClient transportClient;
String index = "website"; //相当于数据库
String type = "blog"; //相当于表, Document相当于行,field相当于列
//默认的集群名:elasticsearch,需要在config/elasticsearch.yml中看是否集群名为:elasticsearch,不是则修改正确
String esCluster="elasticsearchliu";
public ESClient() {
initClient();
}
private void initClient() {
if (transportClient == null) {
/**
* 1:通过 setting对象来指定集群配置信息
*/
Settings setting = Settings.builder()
.put("cluster.name", esCluster)//指定集群名称
.put("client.transport.sniff", true)//启动嗅探功能,这样只需要指定集群中的某一个节点(不一定是主节点),然后会加载集群中的其他节点,这样只要程序不停即使此节点宕机仍然可以连接到其他节点。
.build();
/**
* 2:创建客户端
* 通过setting来创建,若不指定则默认链接的集群名为elasticsearch
* 127.0.0.1需要修改config/elasticsearch.yml中的network.host
* 链接使用tcp协议即9300(java代码链接需用9300,HTTP连接需要9200)
*/
transportClient = TransportClient.builder().settings(setting).build();
// transportClient = new PreBuiltTransportClient(setting);
//若是集群,需要循环addTransportAddresses方法
TransportAddress transportAddress = new InetSocketTransportAddress(InetAddresses.forString("127.0.0.1"), 9300);
transportClient.addTransportAddresses(transportAddress);
}
}
public void close() {
if (transportClient != null) {
transportClient.close();
}
}
/**
* 获取索引库文档总数
*
* @return
*/
public long getDocCount() {
return transportClient.prepareCount(index).get().getCount();
}
public String getDoc(){
GetResponse getResponse = transportClient.prepareGet(index, type, "1").get();
return getResponse.getSourceAsString();
}
public void addDoc(String json){
IndexResponse indexResponse = transportClient.prepareIndex(index, type,"1").setSource(json).get();
System.out.println(indexResponse.getVersion());
}
public void deleteDoc(){
DeleteResponse deleteIndexResponse = transportClient.prepareDelete(index,type,"1").get();
}
public void updateDoc(){
UpdateResponse updateResponse = transportClient.prepareUpdate(index,type,"1").get();
}
public static void main(String[] args) {
ESClient client = new ESClient();
Map<String,Object> map = new HashMap();
map.put("name","小宇");
map.put("age","18");
String json = JSON.toJSONString(map);
client.addDoc(json);
client.deleteDoc();
System.out.println(client.getDoc());
System.out.println(client.getDocCount());
}
}
批量操作ES(批量新增)
//批量新增
public void insertBatch(){
BulkRequest bulkRequest = new BulkRequest();
BulkRequestBuilder builder = transportClient.prepareBulk();
List<Map<String,Object>> list = new ArrayList<>();
Map<String,Object> map = new HashMap();
map.put("color","白色");
map.put("neck","迪奥");
Map<String,Object> map1 = new HashMap();
map1.put("hand","手链");
Map<String,Object> map3 = new HashMap();
map3.put("hand","我带着手链呢");
list.add(map);
list.add(map1);
list.add(map3);
try{
int i =1;
for( Map<String,Object> map2 : list){
i++;
IndexRequest indexRequest = new IndexRequest(index,type,String.valueOf(i));
System.out.println("==list.iterator().next():"+JsonUtils.convertObject2Json(map2));
indexRequest.source( JSON.toJSONString(map2));
bulkRequest.add(indexRequest);
}
//执行完批量新增后,立即查询是查不到的,因为ES是分片异步的
transportClient.bulk(bulkRequest);
// }
}catch (Exception e){
System.out.println("=====error :"+e.getLocalizedMessage());
}
}
分词查询
//查询所有的文档
public SearchHit[] getAll(){
SearchResponse searchResponse = transportClient.prepareSearch(index).setTypes(type).setQuery(QueryBuilders.matchAllQuery()).get();
return searchResponse.getHits().hits();
}
//根据文字来查询
public SearchHit[] getStrByStr(){
SearchResponse searchResponse = transportClient.prepareSearch(index).setTypes(type).setQuery(QueryBuilders.queryStringQuery("迪奥手链")).get();
System.out.println("======命中对象个数为:"+searchResponse.getHits().getTotalHits());
return searchResponse.getHits().hits();
}
// ES分片异步1秒,执行完批量新增后,立马查询,是查不到的
SearchHit[] searchHits = client.getAll();
for(SearchHit hit : searchHits){
System.out.println("======hit:"+ hit.getSourceAsString());
}
SearchHit[] searchHits2 = client.getStrByStr();
for(SearchHit hit : searchHits2){
System.out.println("======hit:"+ hit.getSourceAsString());
}
结果: