使用Rransport操作es
- 导包
使用transport客户端时,不能引入springboot中的es依赖

<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>transport</artifactId>
<version>5.2.2</version>
</dependency>
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>5.2.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.7</version>
</dependency>
- application-es.properties配置
elasticsearch.host=127.0.0.1
elasticsearch.port=9300
elasticsearch.cluster-name=elasticsearch
@Configuration
@PropertySource({"classpath:application-es.properties"})
@ConfigurationProperties(prefix = "elasticsearch")
public class EsConfig {
@Value("${elasticsearch.host}")
private String host;
@Value("${elasticsearch.port}")
private int port;
@Value("${elasticsearch.cluster-name}")
private String clusterName;
@Bean
public TransportClient getClient() throws UnknownHostException {
System.out.println("---------------init es client");
InetSocketTransportAddress node = new InetSocketTransportAddress(
InetAddress.getByName(host),port
);
Settings setttings = Settings.builder()
.put("client.transport.sniff", true)
.put("cluster.name", clusterName).build();
TransportClient client = new PreBuiltTransportClient(setttings);
client.addTransportAddress(node);
return client;
}
}
public void createIndex() {
boolean flag =client.admin().indices().exists(
new IndicesExistsRequest()
.indices(new String[]{INDEX}))
.actionGet().isExists();
if (!flag) {
IndexRequestBuilder builder1 = client.prepareIndex(INDEX, TYPE);
}
List<Course> courseList = courseService.findAll();
BulkRequestBuilder req = client.prepareBulk();
Map<String, Object> map =null;
for (Course course : courseList) {
map = new HashMap<>();
map.put("id", course.getId());
map.put("coursename", course.getCoursename());
map.put("intro", course.getIntro());
req.add(client.prepareIndex(INDEX, TYPE,course.getId().toString()).setSource(map));
}
req.setRefreshPolicy(WriteRequest.RefreshPolicy.IMMEDIATE);
BulkResponse response = req.get();
if ( response.hasFailures()){
throw new RuntimeException("数据插入失败");
}
}
}
public ArrayList<Object> change(QueryCourse queryCourse) {
SearchRequestBuilder builder = client.prepareSearch(INDEX).setTypes(TYPE);
BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
queryBuilder.must(QueryBuilders.matchQuery("coursename", queryCourse.getName()));
builder.setQuery(queryBuilder);
builder.setSize(2);
SearchResponse searchResponse = builder.get();
SearchHits hits = searchResponse.getHits();
SearchHit[] hits1 = hits.getHits();
ArrayList<Object> list = new ArrayList<>();
for (SearchHit h : hits1) {
list.add(h.getSource());
}
return list;
}