天天看点

[Elasticsearch基础]-- Java链接elasticsearch的api

官方参考文档:​​https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/index.html​​

编写java项目进行测试:

1\导入项目需要的elasticsearch----->jar包

[Elasticsearch基础]-- Java链接elasticsearch的api
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
import
import
import
import
import
import
import
import
import
import
import
public class
public static void main(String[] args) throws
settings
//设置elasticesearch的集群名称
"cluster.name", "hh15Elastic").build();
client = TransportClient.builder().settings(settings).build()
//端口号有时是9300,有时是9200,具体需要查看启动elasticsearch的log信息中的transport值
new InetSocketTransportAddress(InetAddress.getByName("hh15"), 9300))
new InetSocketTransportAddress(InetAddress.getByName("hh16"), 9300))
new InetSocketTransportAddress(InetAddress.getByName("hh17"), 9300));
//索引是bjcom
response = client.prepareSearch("bjcom")
//type是employee
"employee")
DFS_QUERY_THEN_FETCH)
//注意字段需要全部为小写,因为不区分大小写
"first_name","john"))             // Query
"age").from(1).to(30))     // Filter,分页大小
true)
                .execute()
                .actionGet();
hits = response.getHits();
hits1 = hits.getHits();
for(SearchHit hit : hits1){
           //返回的json字符串
out.println("結果:"+hit.getSourceAsString());
        }
    }
}
 
运行