Elasticsearch JavaApi
官网JavaApi地址:https://www.elastic.co/guide/en/elasticsearch/client/java-api/current/java-search.html
博客:http://blog.csdn.net/molong1208/article/details/50512149
1.创建索引与数据
把json字符写入索引,索引库名为twitter、类型为tweet,id为1
语法
import static org.elasticsearch.common.xcontent.XContentFactory.*; IndexResponse response = client.prepareIndex("twitter", "tweet", "1")
.setSource(jsonBuilder()
.startObject()
.field("user", "kimchy")
.field("postDate", new Date())
.field("message", "trying out Elasticsearch")
.endObject()
)
.get();
相关用例
public static boolean create(String index, String type, @Nullable String id,String json){ //index:索引库名
//type:类型
//id:文档的id
//json:json字符串
//response.isCreated():创建是否成功
IndexResponse response = client.prepareIndex(index, type, id)
// .setSource("{ \"title\": \"Mastering ElasticSearch\"}")
.setSource(json)
.execute().actionGet(); return response.isCreated(); }
2.删除索引与数据
索引库名为twitter、类型为tweet,id为1
语法
DeleteResponse response = client.prepareDelete("twitter", "tweet", "1").get();
相关用例
public static boolean remove(String index, String type, String id){ //index:索引库名
//type:类型
//id:文档的id
//response.isFound():是否删除成功
DeleteResponse response = client.prepareDelete(index, type, id).get(); return response.isFound(); }
3.修改数据
你可以创建一个UpdateRequest并将其发送到客户端:
UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index("index");
updateRequest.type("type");
updateRequest.id("1");
updateRequest.doc(jsonBuilder()
.startObject()
.field("gender", "male")
.endObject());
client.update(updateRequest).get();
相关用例
public static boolean update(String index, String type, String id,XContentBuilder endObject)
throws IOException, InterruptedException, ExecutionException{ // XContentBuilder endObject = XContentFactory.jsonBuilder()
// .startObject()
// .field("name", "jackRose222")
// .field("age", 28)
// .field("address","上海徐家汇")
// .endObject(); //index:索引库名
//type:类型
//endObject:使用JSON格式返回内容生成器 UpdateRequest updateRequest = new UpdateRequest();
updateRequest.index(index);
updateRequest.type(type);
updateRequest.id(id);
updateRequest.doc(endObject);
UpdateResponse updateResponse = client.update(updateRequest).get(); return updateResponse.isCreated(); }
也可以用prepareUpdate()
方法
client.prepareUpdate("ttl", "doc", "1")
.setDoc(jsonBuilder()
.startObject()
.field("gender", "male")
.endObject())
.get();
相关用例
public static boolean update2(String index, String type, String id,
Map<String,Object> fieldMap) throws IOException, InterruptedException, ExecutionException{ //index:索引库名
//type:类型
//endObject:使用JSON格式返回内容生成器 //使用JSON格式返回内容生成器
XContentBuilder xcontentbuilder = XContentFactory.jsonBuilder(); if(fieldMap!=null && fieldMap.size() >0){
xcontentbuilder.startObject(); for (Map.Entry<String, Object> map : fieldMap.entrySet()) {
if(map != null){
xcontentbuilder.field(map.getKey(),map.getValue());
}
} xcontentbuilder.endObject(); UpdateResponse updateResponse = client.prepareUpdate(index, type, id)
.setDoc(xcontentbuilder)
.get(); return updateResponse.isCreated();
} return false; }
4.查询
4.1搜索API允许一个执行一个搜索查询,返回搜索结果匹配的查询。它可以跨越一个或多个指标和执行一个或多个类型。查询可以使用查询提供的Java API。搜索请求的主体使用SearchSourceBuilder构建。这是一个例子:
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.index.query.QueryBuilders.*;
SearchResponse response = client.prepareSearch("index1", "index2")
.setTypes("type1", "type2")
.setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
.setQuery(QueryBuilders.termQuery("multi", "test")) // Query
.setPostFilter(QueryBuilders.rangeQuery("age").from(12).to(18)) // Filter
.setFrom(0).setSize(60).setExplain(true)
.get();
请注意,所有参数都是可选的。这是最小的搜索你可以写
// MatchAll on the whole cluster with all default options
SearchResponse response = client.prepareSearch().get();
尽管Java API定义了额外的搜索类型QUERY_AND_FETCH DFS_QUERY_AND_FETCH,这些模式内部优化和不应该由用户显式地指定的API。
相关用例
public static SearchResponse search(String index, String type) { // 查询全部
// SearchResponse response2 =
// client.prepareSearch().execute().actionGet(); // 按照索引与类型查询
//index:索引库名
//type:类型
SearchResponse response = client.prepareSearch(index).setTypes(type)
// .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
// .setQuery(QueryBuilders.termQuery("multi", "test")) // Query
// .setFrom(0)
// .setSize(5)
// .setExplain(true)
.execute().actionGet();
return response;
}
4.2多条件查询
http://blog.csdn.net/zx711166/article/details/77847120
public class EsBool{
public void BoolSearch(TransportClient client){
//多条件设置
MatchPhraseQueryBuilder mpq1 = QueryBuilders
.matchPhraseQuery("pointid","W3.UNIT1.10LBG01CP301");
MatchPhraseQueryBuilder mpq2 = QueryBuilders
.matchPhraseQuery("inputtime","2016-07-21 00:00:01");
QueryBuilder qb2 = QueryBuilders.boolQuery()
.must(mpq1)
.must(mpq2);
SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
sourceBuilder.query(qb2);
//System.out.println(sourceBuilder.toString()); //查询建立
SearchRequestBuilder responsebuilder = client
.prepareSearch("pointdata").setTypes("pointdata");
SearchResponse myresponse=responsebuilder
.setQuery(qb2)
.setFrom(0).setSize(50)
.addSort("inputtime", SortOrder.ASC)
//.addSort("inputtime", SortOrder.DESC)
.setExplain(true).execute().actionGet();
SearchHits hits = myresponse.getHits();
for(int i = 0; i < hits.getHits().length; i++) {
System.out.println(hits.getHits()[i].getSourceAsString()); }
}
}
Elasticsearch JavaApi的更多相关文章
- ElasticSearch(java) 创建索引
搜索]ElasticSearch Java Api(一) -创建索引 标签: elasticsearchapijavaes 2016-06-19 23:25 33925人阅读 评论(30) 收藏 举报 ...
- Elasticsearch的javaAPI之percolator
Elasticsearch的javaAPI之percolator percolator同意一个在index中注冊queries,然后发送包括doc的请求,返回得到在index中注冊过的而且匹配doc的 ...
- elasticsearch的javaAPI之query
elasticsearch的javaAPI之query API the Search API同意运行一个搜索查询,返回一个与查询匹配的结果(hits). 它能够在跨一个或多个index上运行, 或者一 ...
- Elasticsearch深入搜索之全文搜索及JavaAPI使用
一.基于词项与基于全文 所有查询会或多或少的执行相关度计算,但不是所有查询都有分析阶段. 和一些特殊的完全不会对文本进行操作的查询(如 bool 或 function_score )不同,文本查询可以 ...
- 通过Shell命令与JavaAPI读取ElasticSearch数据 (能力工场小马哥)
主要内容: 通过JavaAPI和Shell命令两种方式操作ES集群 集群环境: 两个 1,未配置集群名称的单节点(模拟学习测试环境); 2,两个节点的集群(模拟正常生产环境). JDK8+Elasti ...
- Elasticsearch的javaAPI之get,delete,bulk
Elsasticsearch的javaAPI之get get API同意依据其id获得指定index中的基于json document.以下的样例得到一个JSON document(index为twi ...
- Elasticsearch的javaAPI之query dsl-queries
Elasticsearch的javaAPI之query dsl-queries 和rest query dsl一样,elasticsearch提供了一个完整的Java query dsl. 查询建造者 ...
- elasticsearch的javaAPI之index
Index API 原文:http://www.elasticsearch.org/guide/en/elasticsearch/client/java-api/current/index_.html ...
- ElasticSearch的javaAPI之Client
翻译的原文:http://www.elasticsearch.org/guide/en/elasticsearch/client/java-api/current/client.html#node-c ...
随机推荐
- The Singularity is Near---预测人工智能,科技走向的神书---奇点临近
比尔盖茨评价本文作者: 雷·库兹韦尔是我所知道的预测人工智能未来最权威的人.他的这本耐人寻味的书预测未来信息技术得到空前发展,将促使人类超越自身的生物极限--以我们无法想象的方式超越我们的生命. 中文 ...
- java常用集合类详解(有例子,集合类糊涂的来看!)
Framework集合框架是一个统一的架构,用来表示和操作集合.集合框架主要是由接口,抽象类和实现类构成.接口:蓝色:实现类:红色Collection|_____Set(HashSet)| ...
- maven中去掉单元测试的配置
如果是在命令行中去掉测试,可以在命令行中输入:mvn install -Dmaven.test.skip=true 在pom.xml <plugins> <plugin& ...
- Linux Android 多点触摸协议 原文出自【比特网】,转载请保留原文链接:http://soft.chinabyte.com/os/71/12306571.shtml
为了使用功能强大的多点触控设备,就需要一种方案去上报用户层所需的详细的手指触摸数据.这个文档所描述的多点触控协议可以让内核驱动程序向用户层上报任意多指的数据信息. 使用说明 单点触摸信息是以ABS承载 ...
- Python学习笔记 - dict和set
dict #!/usr/bin/env python3 # -*- coding: utf-8 -*- #dict >>> d = {'Michael': 95, 'Bob': 75 ...
- Ubuntu 14 安装Skype 4.3
Ubuntu 14 安装Skype 4.3Step 1: 删除老版本sudo apt-get remove skype skype-bin:i386 skype:i386 sudo apt-get i ...
- 关于学习MMU的一点感想
MMU的一个主要服务是能把各个人物作为各自独立的程序在其自己的虚拟存储空间中运行. 虚拟存储器系统的一个重要特征是地址重定位.地址重定位是将处理器核产生的地址转换到主存的不同地址,转换由MMU硬件完成 ...
- 供应商信息全SQL
SELECT hou.name, pv.vendor_name 供应商, pv.party_id, pvs.vendor_site_id, pvs.terms_id, pv.vendor_name_a ...
- 【一天一道LeetCode】#328 Odd Even Linked List
一天一道LeetCode系列 (一)题目 Given a singly linked list, group all odd nodes together followed by the even n ...
- 程序员编程艺术:第三章续、Top K算法问题的实现
程序员编程艺术:第三章续.Top K算法问题的实现 作者:July,zhouzhenren,yansha. 致谢:微软100题实现组,狂想曲创作组. 时间:2011年05月08日 ...