官方参考文档:https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/index.html
编写java项目进行测试:
1\导入项目需要的elasticsearch----->jar包
2\编写测试类:TestJavaElasticsearch.java
首先在elasticsearch中创建索引
#创建索引
curl -XPOST http://hh15:9200/bjcom/employee/1 -d'
{
"first_name" : "John",
"last_name" : "Smith",
"age" : 25,
"about" : "I love to go rock climbing",
"interests": [ "sports", "music" ]
}'
编写java类
package com.test;
import java.net.InetAddress;
import java.net.UnknownHostException;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
public class Testes {
public static void main(String[] args) throws UnknownHostException {
Settings settings = Settings.settingsBuilder()
//设置elasticesearch的集群名称
.put("cluster.name", "hh15Elastic").build();
Client client = TransportClient.builder().settings(settings).build()
//端口号有时是9300,有时是9200,具体需要查看启动elasticsearch的log信息中的transport值
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("hh15"), 9300))
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("hh16"), 9300))
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("hh17"), 9300));
//索引是bjcom
SearchResponse response = client.prepareSearch("bjcom")
//type是employee
.setTypes("employee")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
//注意字段需要全部为小写,因为不区分大小写
.setQuery(QueryBuilders.termQuery("first_name","john")) // Query
.setPostFilter(QueryBuilders.rangeQuery("age").from(1).to(30)) // Filter,分页大小
.setFrom(0).setSize(60).setExplain(true)
.execute()
.actionGet();
SearchHits hits = response.getHits();
SearchHit[] hits1 = hits.getHits();
for(SearchHit hit : hits1){
//返回的json字符串
System.out.println("結果:"+hit.getSourceAsString());
}
}
}
运行