初学elasticsearch2.3.3,以下是在学习过程中学到的,初步学习,有什么不到的地方,请大家多指教,后期深入学习的时候会慢慢完善这篇博客的
1、maven配置
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>2.3.3</version>
</dependency>
2、client初始化
public class EsClient {
private static String host = "*.*.*.*";#elasticsearch服务器
private static Integer port = 9300;
private static String clusterName = "my-application";#集群名字
private static Boolean transportSniff = true;
private static Client client = null;
private static Settings settings = Settings.settingsBuilder()
.put("cluster.name", clusterName)
.put("client.transport.sniff", transportSniff);//自动嗅探整个集群的状态,把集群中其它机器的ip地址加到客户端中
. build();
public static Client getClient() throws UnknownHostException { #此处采用单利返回client
if(client!=null){
synchronized (client) {
if(client!=null){
TransportClient.builder().settings(settings).build()
.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName(host), port));
}
}
}
return client;
}
}
3、elasticsearch添加数据
public static Boolean add(GifEntity entity){
logger.error("向es里面添加数据>>>"+entity);
model.setLastUpdateTime(new Date());
model.setCreateTime(new Date());
IndexResponse indexResponse = EsClient.getClient().prepareIndex(INDEX_NAME, GIF_INFO_TYPE,""+entity.getGifId()).setSource(JsonUtils.toJSON(entity)).get();#此处指定id,以INDEX_NAME + GIF_INFO_TYPE +id联合保证唯一
return indexResponse.isCreated();#返回是否创建成功
}
4、elasticsearch 根据id删除
public static Boolean delete(Integer gifId){
DeleteResponse deleteResponse = EsClient.getClient().prepareDelete(INDEX_NAME, GIF_INFO_TYPE, ""+gifId).execute().actionGet();
return deleteResponse.isFound(); #返回删除是否成功
}
5、根据id查询详情
public static GifEntity detail(Integer gifId){
GetResponse getReponse = EsClient.getClient().prepareGet(INDEX_NAME, GIF_INFO_TYPE, ""+gifId).execute().actionGet(); //INDEX_NAME GIF_INFO_TYPE+id联合唯一
if(getReponse.isExists()){
return JsonUtils.change(getReponse.getSourceAsString(), GifEntity.class);
}else{
return null;
}
}
6、修改es数据
public static Boolean update(GifEntity entity){
try {
GifEsModel model = JsonUtils.change(entity, GifEsModel.class);
model.setLastUpdateTime(new Date());
UpdateResponse updateResponse = EsClient.getClient().prepareUpdate(INDEX_NAME, GIF_INFO_TYPE,
""+model.getGifId()).setDoc(JsonUtils.toJSON(model)).execute().get();//以JSON字符串形式来进行更新
return updateResponse.isCreated();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
public static Boolean updateLastUpdateTime(Integer gifId){
try {
UpdateResponse updateResponse = EsClient.getClient().prepareUpdate(INDEX_NAME, GIF_INFO_TYPE, ""+gifId)
.setDoc(XContentFactory.jsonBuilder().startObject().field("lastUpdateTime", new Date()).endObject()).execute().get();//更新局部对象
return updateResponse.isCreated();
} catch (InterruptedException | ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("出异常了...");
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("出异常了..111.");
return false;
}
}
7、根据条件随机获取N条数据
public static ResultModel getRandomGif(String tags,String uuid,Integer page,Integer pageSize){//根据tags来进行搜索,UUID做一致性随机
String []tagArr = tags.split(",");//中间以逗号分隔来做多个查询条件
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
RandomScoreFunctionBuilder scoreFunctionBuilder = new RandomScoreFunctionBuilder();
scoreFunctionBuilder.setWeight(1);//指定权重,我这里只是为了随机,所以权重都是相同的
if(uuid!=null&&!uuid.equals("")){
scoreFunctionBuilder.seed(uuid);//如果在多次分页查询中,seed一致,那么每次分页随机出来的数据不会重复,成为一致性随机,否则的话随机出来的数据会出现重复
}else{
scoreFunctionBuilder.seed(UUID.randomUUID().toString());
}
FunctionScoreQueryBuilder q1 = new FunctionScoreQueryBuilder(boolQueryBuilder);
for(String tag:tagArr){
if(tag!=null&&!tag.trim().equals("")){
boolQueryBuilder.must(QueryBuilders.termQuery("tags_index", tag.trim().toLowerCase()));
q1.add(QueryBuilders.termQuery("tags_index", tag.trim().toLowerCase()), scoreFunctionBuilder);
}
}
boolQueryBuilder.must(QueryBuilders.termQuery("isDelete", "0"));
boolQueryBuilder.must(QueryBuilders.termQuery("isPublic", "1"));
q1.scoreMode("sum");
String str = q1.toString();
str = str.replace("query", "filter");//此处讲query查询改为filter,随机不用进行分值计算,暂时未找到如何直接用filter的,所以此处采用了磁环方法
Map map = JsonUtils.change(str, Map.class);
SearchRequestBuilder searchRequestBuilder = EsClient.getClient().prepareSearch(INDEX_NAME).setTypes(GIF_INFO_TYPE)
.setQuery(map);
SearchResponse searchResponse = searchRequestBuilder.setFrom((page - 1) * pageSize)//分页起始位置(跳过开始的n个)
.setSize(pageSize)//本次返回的文档数量
// .addFields("gifId","tags","name","gifUrl").
.execute().actionGet();//执行搜索
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
long count = searchResponse.getHits().getTotalHits();
for(SearchHit hit:searchResponse.getHits()){
@SuppressWarnings("unchecked")
Map<String,Object> entity = JsonUtils.change(hit.sourceAsString(), Map.class);
list.add(entity);
entity = null;
}
return CommonUtil.returnModel(true, "", list, Integer.valueOf(""+count));
}
8、根据前缀搜索及获取数量
使用条件 下拉框自动补全功能,同时显示数量(采用Bucket )
public static List<Map<String,Object>> getSimilarCount(String tag){
AggregationBuilder aggregation = AggregationBuilders
.terms("agg").field("tags_index").include(tag+".*")//指定聚合的时候以tag开头
.subAggregation(
AggregationBuilders.topHits("top").setSize(1)
);
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
boolQueryBuilder.must(QueryBuilders.prefixQuery("tags_index", tag))//tags_index 以tag开头的查询
.must(QueryBuilders.termQuery("isDelete", "0"))
.must(QueryBuilders.termQuery("isPublic", "1"));
SearchRequestBuilder request;
request = EsClient.getClient().
prepareSearch(INDEX_NAME).setTypes(GIF_INFO_TYPE)
.setQuery(boolQueryBuilder)
.addAggregation(aggregation);
SearchResponse r = request.get();
Terms term = r.getAggregations().get("agg");
long docCount = 0;
String key = "";
for (Terms.Bucket entry : term.getBuckets()) {
key = ""+entry.getKey(); // bucket key
docCount = entry.getDocCount(); // Doc count
Map<String,Object> map = new HashMap<String,Object>();
map.put("tagName", key);
map.put("count", docCount);
list.add(map);
}
return list;
}
//默认以聚合出来的数量倒叙
初步学习,记录一下,随后深入学习的时候继续完善