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 ... 
随机推荐
- C#神器 委托 + Unity神器 协程
			作为源生的C#程序员,可能已经非常了解委托(delegate).行动(Action)以及C#的事件了,不过作为一个半道转C#的程序员而言,这些东西可能还是有些陌生的,虽然委托并非是C#独创,亦非是首创 ... 
- 使用go reflect实现一套简易的rpc框架
			go jsonrpc 在实际项目中,我们经常会碰到服务之间交互的情况,如何方便的与远端服务进行交互,就是一个需要我们考虑的问题. 通常,我们可以采用restful的编程方式,各个服务提供相应的web接 ... 
- C语言--字符串和数字的相互转换
			1.数字转换为字符串 sprintf 跟printf 在用法上几乎一样,只是打印的目的地不同而已,前者打印到字符串中,后者则直接在命令行上输出. sprintf 是个变参函数,定义如下: int sp ... 
- 解决在onCreate()过程中获取View的width和Height为0的方法
			最近在看Android底层代码的view绘制原理的时候讲到一个很有意思的事情,也是我几年前刚开始学习Android开发的时候比较纳闷的一个问题,如果你不理解Android的底层绘制,请看我之前一片文章 ... 
- 《java入门第一季》之正则表达式常见规则
			正则表达式规则不用记住,只是知道是做什么用的即可.常见规则如下: A:字符 x 字符 x.举例:'a'表示字符a \\ 反斜线字符. \n 新行(换行)符 ('\u000A') (\\n来表示换行) ... 
- mysql进阶(四)mysql中select
			mysql中select * for update 注: FOR UPDATE 仅适用于InnoDB,且必须在事务区块(BEGIN/COMMIT)中才能生效. 作用 锁定该语句所选择到的对象.防止在 ... 
- mpi中的广播
			MPI可以实现一对多的集合通信,最常用的是广播:某个进程将数据广播到所有其他进程,最终的结果就是每个进程都有一份广播的数据.MPICH中的广播函数是MPI_Bcast(void* buffer,int ... 
- 【公开课】【阿里在线技术峰会】何登成:AliSQL性能优化与功能突破的演进之路
			MySQL的公开课,可能目前用不上这些,但是往往能在以后想解决方案的时候帮助到我.以下是阿里对公开课的整理 摘要: 本文根据阿里高级数据库专家何登成在首届阿里巴巴在线技术峰会上的分享整理而成.他主要介 ... 
- STL的容器算法迭代器的设计理念
			1) STL的容器通过类模板技术,实现数据类型和容器模型的分离. 2) STL的迭代器技术实现了遍历容器的统一方法:也为STL的算法提供了统一性. 3) STL的函数对象实现了自定义数据类型的算法运算 ... 
- 手动将jar添加到maven仓库中
			 1.将jar放到E:\workspace\lib中.如下图: 2.编写pom.xml文件,定义jfinal的坐标. <project xmlns="http://maven.ap ... 
