希望给同样遇见es的你带来帮助,也希望彼此有更多的讨论
版本选择6.4.3
1-Java 客户端的使用 (上)
建立连接
增删改数据
测试
1-引入MAVEN依赖:
使用官方的Java High Level REST
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-high-level-client</artifactId>
<version>6.4.3</version>
</dependency>
2-建立连接
- 我的项目依赖springboot,因此会先把客户端当成一个bean来使用。
@Bean
public RestHighLevelClient client(){
RestHighLevelClient client = new RestHighLevelClient(
RestClient.builder(
new HttpHost("192.168.88.130", 9200, "http")));
return client;
}
3-增删改数据
- 先定义接口和实体类已经需要的常量信息
public interface SearchService {
//索引操作
void createOrUpdate(CometIndex cometIndex);
void remove(Long cometId);
//查询 接口
List <CometIndexVO> query(RentSearch rentSearch);
//自动补全接口
List<String> suggest(String prefix);
}
@Getter
@Setter
public class CometIndex {
private Long cometId; //唯一标示
private String title; //标题
private String author; //原创者
private String editor; //责任编辑
private String category; //分类
private String description; //描述
private String content; //内容
private Date createTime; //创建时间
private List<CometSuggest> suggest; //固定格式 ES
}
public class CometIndexKey {
public static final String INDEX_NAME="comet";
public static final String COMET_ID="cometId"; //唯一标示
public static final String TITLE="title"; //标题
public static final String AUTHOR="author"; //原创者
public static final String EDITOR="editor"; //责任编辑
public static final String CATEGORY="category"; //分类
public static final String DESCRIPTION="description"; //描述
public static final String CONTENT="content"; //内容
public static final String CREATE_TIME="createTime"; //创建时间
}
@Getter
@Setter
public class CometSuggest {
private String input;
private int weight=10;//权重
}
- 实现增删改
@Autowired
private ObjectMapper objectMapper;
@Autowired
private RestHighLevelClient client;
@Override
public void createOrUpdate(CometIndex cometIndex) {
//判断是否已经存在
long id = cometIndex.getCometId();
//构建查询
SearchRequest searchRequest = new SearchRequest();
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.termQuery(CometIndexKey.COMET_ID, id));
searchRequest.source(searchSourceBuilder);
try {
SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
long totalHit = searchResponse.getHits().getTotalHits();
log.info("create index before totalHit:{}", totalHit);
boolean success = false;
if (totalHit == 0) {
success = create(cometIndex);//新增数据
} else if (totalHit == 1) {
String esId = searchResponse.getHits().getAt(0).getId();//获取ID
success = update(esId, cometIndex);//更新数据
} else {//同一个数据存了多个
success = deleteAndCreate(totalHit, cometIndex);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private boolean create(CometIndex cometIndex) {
log.info("create");
if (!updateSuggest(cometIndex)) {
return false;
}
try {
IndexRequest indexRequest = new IndexRequest(CometIndexKey.INDEX_NAME, CometIndexKey.INDEX_NAME)
.source(objectMapper.writeValueAsString(cometIndex), XContentType.JSON);
IndexResponse response = client.index(indexRequest, RequestOptions.DEFAULT);
if (response.getResult() == DocWriteResponse.Result.CREATED) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
log.info("Error Index with comet:{}", cometIndex.getCometId());
return false;
}
}
private boolean update(String esId, CometIndex cometIndex) {
log.info("update");
if (!updateSuggest(cometIndex)) {
return false;
}
try {
UpdateRequest updateRequest = new UpdateRequest(CometIndexKey.INDEX_NAME, CometIndexKey.INDEX_NAME, esId)
.doc(objectMapper.writeValueAsString(cometIndex), XContentType.JSON);
UpdateResponse response = client.update(updateRequest, RequestOptions.DEFAULT);
if (response.getResult() == DocWriteResponse.Result.UPDATED) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
log.info("Error update Index with comet:{}", cometIndex.getCometId());
return false;
}
}
private boolean deleteAndCreate(long totalHit, CometIndex cometIndex) {
remove(cometIndex.getCometId());
return create(cometIndex);
}
@Override
public void remove(Long cometId) {
RestClient restClient = client.getLowLevelClient();//获取 low api
String endPoint = "/" + CometIndexKey.INDEX_NAME + "/" + CometIndexKey.INDEX_NAME + "/_delete_by_query";
try {
XContentBuilder builder = XContentFactory.jsonBuilder();
builder.startObject()
.startObject("query")
.startObject("term")
.field(CometIndexKey.COMET_ID, cometId)
.endObject()
.endObject()
.endObject();
IndexRequest indexRequest = new IndexRequest().source(builder);
HttpEntity entity = new NStringEntity(indexRequest.source().utf8ToString(), ContentType.APPLICATION_JSON);
Request request = new Request(
"POST",
endPoint);
request.setEntity(entity);
Response response = restClient.performRequest(request);
log.info("response:{}", response.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
4-测试
@Test
public void createOrUpdate(){
CometIndex cometIndex=new CometIndex();
cometIndex.setCometId(4l);
cometIndex.setAuthor("大王叫我来巡山");
cometIndex.setCategory("question");
cometIndex.setContent("hey es ,我是来自西游记的大魔王,来巡山了。");
cometIndex.setDescription("nothing");
cometIndex.setEditor("cctv");
cometIndex.setTitle("西游记故事新编");
cometIndex.setCreateTime(new Date());
searchService.createOrUpdate(cometIndex);
}
可以修改测试数据进行继续测试。
完整代码后续会提供github地址