官网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的更多相关文章

  1. ElasticSearch(java) 创建索引

    搜索]ElasticSearch Java Api(一) -创建索引 标签: elasticsearchapijavaes 2016-06-19 23:25 33925人阅读 评论(30) 收藏 举报 ...

  2. Elasticsearch的javaAPI之percolator

    Elasticsearch的javaAPI之percolator percolator同意一个在index中注冊queries,然后发送包括doc的请求,返回得到在index中注冊过的而且匹配doc的 ...

  3. elasticsearch的javaAPI之query

    elasticsearch的javaAPI之query API the Search API同意运行一个搜索查询,返回一个与查询匹配的结果(hits). 它能够在跨一个或多个index上运行, 或者一 ...

  4. Elasticsearch深入搜索之全文搜索及JavaAPI使用

    一.基于词项与基于全文 所有查询会或多或少的执行相关度计算,但不是所有查询都有分析阶段. 和一些特殊的完全不会对文本进行操作的查询(如 bool 或 function_score )不同,文本查询可以 ...

  5. 通过Shell命令与JavaAPI读取ElasticSearch数据 (能力工场小马哥)

    主要内容: 通过JavaAPI和Shell命令两种方式操作ES集群 集群环境: 两个 1,未配置集群名称的单节点(模拟学习测试环境); 2,两个节点的集群(模拟正常生产环境). JDK8+Elasti ...

  6. Elasticsearch的javaAPI之get,delete,bulk

    Elsasticsearch的javaAPI之get get API同意依据其id获得指定index中的基于json document.以下的样例得到一个JSON document(index为twi ...

  7. Elasticsearch的javaAPI之query dsl-queries

    Elasticsearch的javaAPI之query dsl-queries 和rest query dsl一样,elasticsearch提供了一个完整的Java query dsl. 查询建造者 ...

  8. elasticsearch的javaAPI之index

    Index API 原文:http://www.elasticsearch.org/guide/en/elasticsearch/client/java-api/current/index_.html ...

  9. ElasticSearch的javaAPI之Client

    翻译的原文:http://www.elasticsearch.org/guide/en/elasticsearch/client/java-api/current/client.html#node-c ...

随机推荐

  1. Django练习——博客系统小试

    在上一篇博客Todolist的基础上(http://blog.csdn.net/hcx25909/article/details/24251427),本周继续进行实践,这次我要搭建一个简单的博客系统. ...

  2. leetcode 20 Valid Parentheses 括号匹配

    Given a string containing just the characters '(', ')', '{', '}', '[' and']', determine if the input ...

  3. UILTView经典知识点练习

    作者:韩俊强   未经允许,请勿转载! 关注博主:http://weibo.com/hanjunqiang 声明:UILTView 指:UILabel 和 UITextField 的复合 #impor ...

  4. SpriteBuilder改变布局后App运行出错代码排查

    原来整个关卡场景放在GameScene.ccb中,后来觉得移到专门的Level.ccb比较好. 移动过后编译运行,只要移动Player的胳膊发射子弹时,Xcode报错: g due to Chipmu ...

  5. (NO.00001)iOS游戏SpeedBoy Lite成形记(九)

    我们回到matchRun方法中去尝试第一次修改,部分代码如下: CCActionMoveBy *moveBy = [CCActionMoveBy actionWithDuration:duration ...

  6. git中failed to push some refs to git问题解决及基本使用

    国庆归来准备试用一下git,在提交代码时遇到时遇到一些问题 提交时使用git push origin master 出现failed to push some refs to git 回想一下,创建该 ...

  7. 使用MTL库求解最小二乘解

    最小二乘计算最优解不管是哪个行业肯定都用到的非常多.对于遥感图像处理中,尤其是对图像进行校正处理,关于控制点的几种校正模型中,都用到最小二乘来计算模型的系数.比如几何多项式,或者通过GCP求解RPC系 ...

  8. Git添加文件改动时出错

    原来的主文件夹中替换了3个子文件夹,每个子文件夹有若干同名文件,总共替换了大概200多个文件吧. 然后在git主文件夹中使用git add .指令出现如下错误: apple@kissAir: iOS$ ...

  9. php opcode缓存

    本文移至:http://www.phpgay.com/Article/detail/classid/2/id/61.html 1.什么是opcode 解释器分析代码之后,生成可以直接运行的中间代码,就 ...

  10. CentOS删除自带的java,安装新java

    [root@localhost ~]# java -version java version "1.4.2″ gij (GNU libgcj) version 4.1.2 20071124 ...