Elasticsearch JavaApi

时间:2022-07-14 06:01:09

官网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()); }
}
}