package com.fill.ElasticTest;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutionException;
import org.apache.lucene.queryparser.flexible.core.builders.QueryBuilder;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequestBuilder;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.reindex.BulkByScrollResponse;
import org.elasticsearch.index.reindex.DeleteByQueryAction;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.metrics.avg.Avg;
import org.elasticsearch.search.aggregations.metrics.max.Max;
import org.elasticsearch.search.aggregations.metrics.min.Min;
import org.elasticsearch.search.aggregations.metrics.sum.Sum;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
/**
* Hello world!
*
*/
public class App
{
public static void main( String[] args )
{
//System.out.println( "Hello World!" );
//1.指定es集群
Settings settings = Settings.builder().put("cluster.name","my-application").build();
//2.创建访问es服务器的客户端
try {
@SuppressWarnings({ "resource", "unchecked" })
TransportClient client = (TransportClient)new PreBuiltTransportClient(settings)
.addTransportAddress(
new InetSocketTransportAddress(InetAddress.getByName("127.0.0.1"), 9300));
/*
String jsonStr = "{" +
"\"name\":\"fefefefe\"," +
"\"description\":\"tabe sd bbb uuu lllvvv\"," +
"}";
IndexResponse response2 = client.prepareIndex("lib","user","3").setSource(jsonStr,XContentType.JSON).get();
*/
XContentBuilder doc = XContentFactory.jsonBuilder()
.startObject()
.field("name","fefefe")
.field("description","tabe sd bbb uuu lllvvv")
.endObject();
/*
IndexResponse response2 = client.prepareIndex("lib","user","3").setSource(doc).get();
System.out.println( response2.status());
DeleteResponse response3 = client.prepareDelete("lib","user","3").get();
System.out.println( response3.status());
*/
// try {
// update(client);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (ExecutionException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//indexUpdate(client);
//bulkDemo(client);
//findDel(client);
//mgetDemo(client);
//matchAllDemo(client);
//matchDemo(client);
termDemo(client);
System.out.println("======================");
//3.数据查询
GetResponse response = client.prepareGet("lib","user","3").execute().actionGet();
//4.得到查询出的数据
//System.out.println( response.getSource);
System.out.println( response.getSourceAsString());
client.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//修改
public static void update(TransportClient client) throws InterruptedException, ExecutionException{
UpdateRequest request = new UpdateRequest();
try {
request.index("lib")
.type("user")
.id("1")
.doc(
XContentFactory.jsonBuilder()
.startObject()
.field("name","xiaoxiaofefefe")
.field("description","78686868")
.endObject()
);
UpdateResponse response = client.update(request).get();
System.out.println( response.status());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//没有就插入有就修改
public static void indexUpdate(TransportClient client){
try {
IndexRequest index = new IndexRequest("lib","user","3").source(
XContentFactory.jsonBuilder()
.startObject()
.field("name","mmxiaoxiaofefefe")
.field("description","4564678686868")
.endObject()
);
UpdateRequest request = new UpdateRequest("lib","user","3").doc(
XContentFactory.jsonBuilder()
.startObject()
.field("name","88mmxiaoxiaofefefe")
.field("description","334564678686868")
.endObject()
).upsert(index);
UpdateResponse response = client.update(request).get();
System.out.println( response.status());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//批量查询
public static void mgetDemo(TransportClient client){
MultiGetResponse response = client.prepareMultiGet()
.add("lib","user","4","5")
.get();
for(MultiGetItemResponse item:response){
GetResponse gr = item.getResponse();
if(gr!=null&&gr.isExists()){
System.out.println( gr.getSourceAsString());
}
}
}
//批量操作
public static void bulkDemo(TransportClient client){
BulkRequestBuilder bulkBuilder = client.prepareBulk();
try {
bulkBuilder.add(client.prepareIndex("lib","user","4").setSource(
XContentFactory.jsonBuilder()
.startObject()
.field("name","4_mmxiaoxiaofefefe")
.field("description","4_334564678686868")
.endObject()
));
bulkBuilder.add(client.prepareIndex("lib","user","5").setSource(
XContentFactory.jsonBuilder()
.startObject()
.field("name","5_mmxiaoxiaofefefe")
.field("description","5_334564678686868")
.endObject()
));
BulkResponse response = bulkBuilder.get();
if(response.hasFailures()){
System.out.println("失败");
}
System.out.println( response.status());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//查找并删除
public static void findDel(TransportClient client){
BulkByScrollResponse response = DeleteByQueryAction.INSTANCE
.newRequestBuilder(client)
.filter(QueryBuilders.matchQuery("description","5_334564678686868"))
.source("lib")
.get();
long count = response.getDeleted();
System.out.println(count);
}
//查找所有
public static void matchAllDemo(TransportClient client){
org.elasticsearch.index.query.QueryBuilder gb = (org.elasticsearch.index.query.QueryBuilder) QueryBuilders.matchAllQuery();
SearchResponse sr = client.prepareSearch("lib").setQuery(gb).setSize(3).get();
SearchHits hits = sr.getHits();
for(SearchHit hit:hits){
System.out.println( hit.getSourceAsString());
}
}
//match query
public static void matchDemo(TransportClient client){
org.elasticsearch.index.query.QueryBuilder gb =(org.elasticsearch.index.query.QueryBuilder) QueryBuilders.matchQuery("description","CBSE Affiliation");
SearchResponse sr = client.prepareSearch("lib").setQuery(gb).setSize(3).get();
SearchHits hits = sr.getHits();
for(SearchHit hit:hits){
System.out.println( hit.getSourceAsString());
}
}
//multimatch query
public static void multMatchDemo(TransportClient client){
org.elasticsearch.index.query.QueryBuilder gb =(org.elasticsearch.index.query.QueryBuilder) QueryBuilders.multiMatchQuery("description","CBSE Affiliation");
SearchResponse sr = client.prepareSearch("lib").setQuery(gb).setSize(3).get();
SearchHits hits = sr.getHits();
for(SearchHit hit:hits){
System.out.println( hit.getSourceAsString());
}
}
//term query
public static void termDemo(TransportClient client){
org.elasticsearch.index.query.QueryBuilder gb =(org.elasticsearch.index.query.QueryBuilder) QueryBuilders.termQuery("name","fefefe");
SearchResponse sr = client.prepareSearch("lib").setQuery(gb).setSize(3).get();
SearchHits hits = sr.getHits();
for(SearchHit hit:hits){
System.out.println( hit.getSourceAsString());
}
}
//terms query
public static void termsDemo(TransportClient client){
org.elasticsearch.index.query.QueryBuilder gb =(org.elasticsearch.index.query.QueryBuilder) QueryBuilders.termsQuery("description","CBSE Affiliation","88mm");
SearchResponse sr = client.prepareSearch("lib").setQuery(gb).setSize(3).get();
SearchHits hits = sr.getHits();
for(SearchHit hit:hits){
System.out.println( hit.getSourceAsString());
}
}
//range query
public static void rangeDemo(TransportClient client){
//range查询
// org.elasticsearch.index.query.QueryBuilder gb =(org.elasticsearch.index.query.QueryBuilder) QueryBuilders.rangeQuery("birthday").from("1990-10-23")
// .to("1999-12-21").format("yyyy-MM-dd");
//前缀查询
// org.elasticsearch.index.query.QueryBuilder gb =(org.elasticsearch.index.query.QueryBuilder) QueryBuilders.prefixQuery("description","CBSE");
//wildcard
// org.elasticsearch.index.query.QueryBuilder gb =(org.elasticsearch.index.query.QueryBuilder) QueryBuilders.wildcardQuery("description","CBSE*");
//fuzzy(自动校验)
// org.elasticsearch.index.query.QueryBuilder gb =(org.elasticsearch.index.query.QueryBuilder) QueryBuilders.fuzzyQuery("description","sang");
//type
// org.elasticsearch.index.query.QueryBuilder gb =(org.elasticsearch.index.query.QueryBuilder) QueryBuilders.typeQuery("user");
//ids
org.elasticsearch.index.query.QueryBuilder gb =(org.elasticsearch.index.query.QueryBuilder) QueryBuilders.idsQuery().addIds("1","3");
SearchResponse sr = client.prepareSearch("lib").setQuery(gb).setSize(3).get();
SearchHits hits = sr.getHits();
for(SearchHit hit:hits){
System.out.println( hit.getSourceAsString());
}
}
//聚合
public static void aggDemo(TransportClient client){
AggregationBuilder agg =AggregationBuilders.max("aggmax").field("age");
AggregationBuilder minv =AggregationBuilders.min("aggmin").field("age");
AggregationBuilder avgv =AggregationBuilders.avg("aggavg").field("age");
AggregationBuilder asum =AggregationBuilders.avg("aggsum").field("age");
SearchResponse sr = client.prepareSearch("lib").addAggregation(agg).get();
SearchResponse srMin = client.prepareSearch("lib").addAggregation(minv).get();
SearchResponse srAvg = client.prepareSearch("lib").addAggregation(avgv).get();
SearchResponse srSum = client.prepareSearch("lib").addAggregation(asum).get();
Max max = sr.getAggregations().get("aggmax");
Min min = srMin.getAggregations().get("aggmin");
Avg avg = srAvg.getAggregations().get("aggavg");
Sum sum = srSum.getAggregations().get("aggsum");
//Avg
max.getValue();
}
//query String
public static void queryDemo(TransportClient client){
//org.elasticsearch.index.query.QueryBuilder gb =(org.elasticsearch.index.query.QueryBuilder) QueryBuilders.queryStringQuery("+change -hejiu");
//org.elasticsearch.index.query.QueryBuilder gb =(org.elasticsearch.index.query.QueryBuilder) QueryBuilders.simpleQueryStringQuery("+change -hejiu");
org.elasticsearch.index.query.QueryBuilder gb =(org.elasticsearch.index.query.QueryBuilder)
QueryBuilders.boolQuery().must(QueryBuilders.matchQuery("description","CBSE")).mustNot(QueryBuilders.matchQuery("name","cbb"))
.should(QueryBuilders.matchQuery("address","bj")).filter(QueryBuilders.rangeQuery("birthday").from("1990-01-01").to("2000-02-22")
.format("yyyy-MM-dd"));
SearchResponse sr = client.prepareSearch("lib").setQuery(gb).setSize(3).get();
SearchHits hits = sr.getHits();
for(SearchHit hit:hits){
System.out.println( hit.getSourceAsString());
}
}
}
附marvin:
4.0.0
com.fill
ElasticTest
0.0.1-SNAPSHOT
jar
ElasticTest
http://maven.apache.org
UTF-8
2.5
aliyun
aliyun
http://maven.aliyun.com/nexus/content/groups/public
junit
junit
3.8.1
test
org.elasticsearch.client
transport
5.5.1
org.slf4j
slf4j-log4j12
1.7.21
test
org.apache.logging.log4j
log4j-api
2.8.2
org.apache.logging.log4j
log4j-core
2.8.2