1.根据ES版本引入相应版本的依赖
<dependency> <groupId>org.elasticsearch.client</groupId> <artifactId>elasticsearch-rest-high-level-client</artifactId> <version>${elasticsearch.version}</version> </dependency>
2.配置相应配置类
import org.apache.http.HttpHost; import org.elasticsearch.client.RequestOptions; import org.elasticsearch.client.RestClient; import org.elasticsearch.client.RestHighLevelClient; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class ElasticSearchConfig { public static final RequestOptions COMMON_OPTIONS; static { RequestOptions.Builder builder = RequestOptions.DEFAULT.toBuilder(); COMMON_OPTIONS = builder.build(); } @Bean public RestHighLevelClient esRestClient(){ RestHighLevelClient client = new RestHighLevelClient( RestClient.builder(new HttpHost("192.168.56.10", 9200, "http"))); return client; } }
3.测试保存
3.1先创建一个User类
@Data class User{ private String name; private Integer age; private String gender; }
3.2进行测试
@Autowired private RestHighLevelClient highLevelClient;
@Test //添加,更新 public void indexData() throws IOException { IndexRequest indexRequest = new IndexRequest("users"); indexRequest.id("1"); //indexRequest.source("name","xs","age",15,"gender","male"); User user = new User(); user.setAge(12); user.setGender("male"); user.setName("xs"); String json = JSON.toJSONString(user); indexRequest.source(json, XContentType.JSON); IndexResponse index = highLevelClient.index(indexRequest, ElasticSearchConfig.COMMON_OPTIONS); System.out.println("index="+index); }
输出得到:index=IndexResponse[index=users,type=_doc,id=1,version=2,result=updated,seqNo=1,primaryTerm=1,shards={"total":2,"successful":1,"failed":0}]
使用Kibana进行搜索:
GET users/_search
发现保存成功:
{
"took" : 200,
"timed_out" : false,
"_shards" : {
"total" : 1,
"successful" : 1,
"skipped" : 0,
"failed" : 0
},
"hits" : {
"total" : {
"value" : 1,
"relation" : "eq"
},
"max_score" : 1.0,