elasticarch6.x与elasticarch7.x配置与使⽤(Java)
前些天看完了⼀本关于elasticarch的书籍,并且做了⼀个elasticarch相关项⽬,对与es也算是有了⼀定程度的了解,不过看书向来都是⼀边看⼀边忘的,以此⽂章记录⼀些es的简单⽤法。
依赖
由于本⼈⽤的es版本为es 7.2的镜像,故所有依赖都是es 7.2 版本。以下为依赖代码。
<dependency>
<groupId>org.elasticarch</groupId>
<artifactId>elasticarch</artifactId>
<version>7.2.0</version>
</dependency>
<!--这个依赖7.x 版本可以不添加,但是由于本⼈代码⽤到,所以不去除-->
<dependency>
<groupId>org.elasticarch.client</groupId>
<artifactId>transport</artifactId>
<version>7.2.0</version>
</dependency>
<dependency>
<groupId>org.elasticarch.client</groupId>
<artifactId>elasticarch-rest-high-level-client</artifactId>
<version>7.2.0</version>
</dependency>
<dependency>
<groupId>org.elasticarch.client</groupId>
<artifactId>elasticarch-rest-client</artifactId>
炫迈妹儿<version>7.2.0</version>
</dependency>
配置
下⾯为ElasticarchConfig的配置代码
import org.apache.http.HttpHost;
import org.elasticarch.client.RestClient;
import org.elasticarch.client.RestClientBuilder;
import org.elasticarch.client.RestHighLevelClient;
import org.ansport.TransportClient;
import ings.Settings;
import ansport.TransportAddress;
import ansport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import t.annotation.Bean;
import t.annotation.Configuration;
import java.InetAddress;
/**
* @Author lidai
* @Date 2020/1/7 16:20
*/
@Configuration
public class ElasticarchConfig {
@Value("${elasticarch.host}")
private String host;
@Value("${elasticarch.port}")
private int port;
职业体验感悟
@Value("${elasticarch.scheme}")
private String scheme;
@Value("${elasticarch.timeout}")
private int timeout;
@Bean(name ="highLevelClient")
public RestHighLevelClient restHighLevelClient(){
/
/可以传httpHost数组
RestClientBuilder builder = RestClient.builder(new HttpHost(host, port, scheme));
builder.tRequestConfigCallback(requestConfigBuilder ->{
//设置超时
return requestConfigBuilder.tSocketTimeout(timeout);
});
return new RestHighLevelClient(builder);
}
/**
* es7 已废弃 TransportClient,但是代码记录中⽤到,故留存。7.x版本可以直接舍弃
*
* @return
*/
@Bean
public TransportClient transportClient(){
try{
珍珠鸟Settings ttings = Settings.builder().put("cluster.name","elasticarch")
.put("ansport.sniff",true)
.build();
TransportClient transportClient =new PreBuiltTransportClient(ttings);
TransportAddress address =new ByName(host), port); transportClient.addTransportAddress(address);
return transportClient;
}catch(Exception e){
e.printStackTrace();
return null;
}
}
}
⼯具类
es 6.x中好像在存储或修改时不能直接使⽤json字符串了(我记得是这样,如果能⽤就更好了),所以需要使⽤XContentBuilder来对字段进⾏处理,以下是⼀个处理的⼯具类
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import nt.XContentBuilder;
import java.io.IOException;
import java.util.Map;
/**
* @Author lidai
* @Date 2020/1/7 18:14
*/
public class ElasticarchUtils {
/**
* 将实体转化为 XContentBuilder 以便存储es
*
* @param xContentBuilder
* @param object
* @return
*/
public static XContentBuilder objectToXContentBuilder(XContentBuilder xContentBuilder, Object object){
try{
JSONObject jsonObject = JSON.JSONString(object));
xContentBuilder.startObject();
for(Map.Entry<String, Object> entry : Set()){
xContentBuilder.Key(), Value());
}
}catch(IOException e){
e.printStackTrace();
}
return xContentBuilder;
}
}
⽰例代码
以下为增删改查的Java⽰例代码 ,⽬前代码都是es6.x版本,7.x版本有时间在加上去。值得注意的是es7.x中 TransportClient类已经过期。所以以下⽰例代码中凡是使⽤TransportClient的⽰例代码均为 elasticarch 6.x 版本。
import com.alibaba.fastjson.JSONObject;
import com.demo.interview.es.domain.ElasticarchPage;
import com.demo.interview.es.domain.Person;
import com.demo.interview.es.utils.ElasticarchUtils;
slf4j.Slf4j;
import org.elasticarch.ElasticarchException;
import org.elasticarch.action.admin.indices.analyze.AnalyzeRequest;
import org.elasticarch.action.admin.indices.analyze.AnalyzeRespon;
import org.elasticarch.action.bulk.BulkRequestBuilder;
import org.elasticarch.action.bulk.BulkRespon;
import org.elasticarch.action.index.IndexRespon;
import org.elasticarch.action.arch.SearchRespon;
import org.elasticarch.action.support.WriteRequest;
import org.elasticarch.action.update.UpdateRespon;
import org.elasticarch.client.RestHighLevelClient;
import org.ansport.TransportClient;
import nt.XContentBuilder;
import nt.XContentFactory;
import org.elasticarch.index.query.BoolQueryBuilder;
import org.elasticarch.index.query.QueryBuilders;
import org.elasticarch.arch.SearchHit;
import org.elasticarch.arch.SearchHit;
import org.elasticarch.arch.SearchHits;
牛脑
import org.elasticarch.arch.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* @Author lidai
* @Date 2020/1/7 18:12
*/
@Slf4j
@RestController
@RequestMapping("/elasticarch")
public class ElasticarchController {
static DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
static DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
static Person person =new Person(1L,"test",20,0, LocalDate.par("2020-01-01").format(formatter),"备注", w().format(formatter2)); final String DEMO_INDEX ="demo_index";
final String DEMO_TYPE ="demo_type";
@Autowired
@Qualifier(value ="highLevelClient")
private RestHighLevelClient highLevelClient;
@Autowired葱姜炒青蟹
private TransportClient transportClient;
中文歌/**
* 新增
*
* @param person
* @throws Exception
*/
public void createIndex(Person person)throws Exception {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder();
怎么更改ipxContentBuilder = ElasticarchUtils.objectToXContentBuilder(xContentBuilder, person);
//创建索引
IndexRespon indexRespon = transportClient.prepareIndex(DEMO_INDEX, DEMO_TYPE, Id().toString())
.tSource(xContentBuilder)
//⽴即⽣效,⽆此需求可以不设置
.tRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
.execute().actionGet();
}
/**
* 修改
*
* @param object
* @throws IOException
*/
public void updateIndex(Person person)throws IOException {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder();
xContentBuilder = ElasticarchUtils.objectToXContentBuilder(xContentBuilder, person);
UpdateRespon updateRespon = transportClient.prepareUpdate(DEMO_INDEX, DEMO_TYPE, Id().toString()) .tRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
.tRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE)
.tDoc(xContentBuilder).get();
}
/**
* 批量修改
*
* @param ids
* @throws IOException
*/
public void batchUpdate(String[] ids)throws IOException {
BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();
for(String id : ids){
bulkRequestBuilder.add(transportClient.prepareUpdate(DEMO_INDEX, DEMO_TYPE, id)
.tDoc(XContentFactory.jsonBuilder().startObject().field("deleted",1).endObject()));
}
BulkRespon respon = bulkRequestBuilder.tRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE).get();
if(respon.hasFailures()){
throw new ElasticarchException(respon.buildFailureMessage());
}
}
/**
* 批量新增
*
* @param persons
* @throws IOException
*/
public void batchInrt(List<Person> persons)throws IOException {
XContentBuilder xContentBuilder = XContentFactory.jsonBuilder();
BulkRequestBuilder bulkRequestBuilder = transportClient.prepareBulk();
//添加es
for(Person person : persons){
/
/注意批量操作时数据为null会报异常
bulkRequestBuilder.add(transportClient.prepareIndex(DEMO_INDEX, DEMO_TYPE, Id().toString()) .tSource(ElasticarchUtils.objectToXContentBuilder(xContentBuilder, person)));
}
BulkRespon respons = ();
if(respons.hasFailures()){
throw new ElasticarchException(respons.buildFailureMessage());
}
}
/**
* 搜索⽰例
*
* @param params
* @return
*/
public ElasticarchPage<Person>archDemo(Map<String, Object> params){
BoolQueryBuilder boolQueryBuilder =new BoolQueryBuilder();
boolQueryBuilder.Query("deleted",0));
String keyword =(String) ("keyword");
Integer news =(Integer) ("news");
Integer status =(Integer) ("status");
Integer columnCategory =(Integer) ("columnCategory");
String year =(String) ("year");
Integer pageSize =(Integer) ("pageSize");
Integer pageNum =(Integer) ("pageNum");
String[] messageColumn ={"messageTitle","messageSource","content","tags","issuer"};
//keyword字段类别搜索
if(news != null && StringUtils.hasText(keyword)){
switch(news){
ca1:
face的音标boolQueryBuilder.must(QueryBuilders.multiMatchQuery(keyword, messageColumn));
break;
ca2:
boolQueryBuilder.must(QueryBuilders.matchQuery("messageTitle", keyword));