elasticsearch Java API汇总
http://blog.csdn.net/changong28/article/details/38445805#comments
3.1 集群的连接
3.1.1 作为Elasticsearch节点
- 代码:
- import static org.elasticsearch.node.NodeBuilder.nodeBuilder;
- import org.elasticsearch.client.Client;
- import org.elasticsearch.node.Node;
- Node node = nodeBuilder().clusterName("escluster2").client(true).
- node();
- Client client = node.client();
3.1.2 使用Transport连接
- 代码:
- import org.elasticsearch.client.transport.TransportClient;
- import org.elasticsearch.common.settings.ImmutableSettings;
- import org.elasticsearch.common.settings.Settings;
- import org.elasticsearch.common.transport.InetSocketTransportAddress;
- Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "escluster2").build();
- TransportClient client = new TransportClient(settings);
- client.addTransportAddress(new InetSocketTransportAddress("127.0.0.1",9300));
3.2 文档的CRUD
3.2.1 查询文档
- 代码:
- GetResponse response = client.prepareGet("library", "book", "1")
- .setFields("title", "_source")
- .execute().actionGet();
3.2.2 索引文档
- 代码:
- import org.elasticsearch.action.index.IndexResponse;
- import org.elasticsearch.client.Client;
- IndexResponse response = client.prepareIndex("library", "book", "2")
- .setSource("{ \"title\": \"Mastering ElasticSearch\"}")
- .execute().actionGet();
3.2.3 更新文档
- 代码:
- import org.elasticsearch.action.update.UpdateResponse;
- import org.elasticsearch.client.Client;
- import java.util.Map;
- import org.elasticsearch.common.collect.Maps;
- Map<String, Object> params = Maps.newHashMap();
- params.put("ntitle", "ElasticSearch Server Book");
- UpdateResponse response = client.prepareUpdate("library", "book", "2")
- .setScript("ctx._source.title = ntitle")
- .setScriptParams(params)
- .execute().actionGet();
3.2.4 删除文档
- 代码:
- import org.elasticsearch.action.delete.DeleteResponse;
- import org.elasticsearch.client.Client;
- DeleteResponse response = client.prepareDelete("library", "book", "2")
- .execute().actionGet();
3.3 Elasticsearch检索
3.3.1 Preparing a query
- 代码:
- import org.elasticsearch.action.search.SearchResponse;
- import org.elasticsearch.client.Client;
- import org.elasticsearch.search.SearchHit;
- SearchResponse response = client.prepareSearch("library")
- .addFields("title", "_source")
- .execute().actionGet();
- for(SearchHit hit: response.getHits().getHits()) {
- <span style="white-space:pre"> </span>System.out.println(hit.getId());
- <span style="white-space:pre"> </span>if (hit.getFields().containsKey("title")) {
- <span style="white-space:pre"> </span>System.out.println("field.title: "+ hit.getFields().get("title").getValue());
- <span style="white-space:pre"> </span>}
- <span style="white-space:pre"> </span>System.out.println("source.title: " + hit.getSource().get("title"));
- }
3.3.2 Building queries
- 代码:
- import org.elasticsearch.index.query.QueryBuilder;
- import org.elasticsearch.index.query.QueryBuilders;
- QueryBuilder queryBuilder = QueryBuilders
- .disMaxQuery()
- .add(QueryBuilders.termQuery("title", "Elastic"))
- .add(QueryBuilders.prefixQuery("title", "el"));
- System.out.println(queryBuilder.toString());
- SearchResponse response = client.prepareSearch("library")
- .setQuery(queryBuilder)
- .execute().actionGet();
3.3.3 Using the match all documents query
- 代码:
- queryBuilder = QueryBuilders.matchAllQuery()
- .boost(11f).normsField("title");
3.3.4 The match query
- 代码:
- queryBuilder = QueryBuilders
- .matchQuery("message", "a quick brown fox")
- .operator(Operator.AND)
- .zeroTermsQuery(ZeroTermsQuery.ALL);
3.3.5 Using the geo shape query
- 代码:
- queryBuilder = QueryBuilders.geoShapeQuery("location",
- ShapeBuilder.newRectangle()
- .topLeft(13, 53)
- .bottomRight(14, 52)
- .build());
3.3.6 Paging query
- 代码:
- SearchResponse response = client.prepareSearch("library")
- .setQuery(QueryBuilders.matchAllQuery())
- .setFrom(10)
- .setSize(20)
- .execute().actionGet();
3.3.7 Sorting
- 代码:
- SearchResponse response = client.prepareSearch("library")
- .setQuery(QueryBuilders.matchAllQuery())
- .addSort(SortBuilders.fieldSort("title"))
- .addSort("_score", SortOrder.DESC)
- .execute().actionGet()
3.3.8 Filtering
- 代码:
- FilterBuilder filterBuilder = FilterBuilders
- .andFilter(
- FilterBuilders.existsFilter("title").filterName("exist"),
- FilterBuilders.termFilter("title", "elastic")
- );
- SearchResponse response = client.prepareSearch("library")
- .setFilter(filterBuilder)
- .execute().actionGet();
3.3.9 Faceting
- 代码:
- FacetBuilder facetBuilder = FacetBuilders
- .filterFacet("test")
- .filter(FilterBuilders.termFilter("title", "elastic"));
- SearchResponse response = client.prepareSearch("library")
- .addFacet(facetBuilder)
- .execute().actionGet();
3.3.10 Highlighting
- 代码:
- SearchResponse response = client.prepareSearch("wikipedia")
- .addHighlightedField("title")
- .setQuery(QueryBuilders.termQuery("title", "actress"))
- .setHighlighterPreTags("<1>", "<2>")
- .setHighlighterPostTags("</1>", "</2>")
- .execute().actionGet();
- for(SearchHit hit: response.getHits().getHits()) {
- <span style="white-space:pre"> </span>HighlightField hField = hit.getHighlightFields().get("title");
- <span style="white-space:pre"> </span>for (Text t : hField.fragments()) {
- <span style="white-space:pre"> </span>System.out.println(t.string());
- <span style="white-space:pre"> </span>}
- }
3.3.11 Suggestions
- 代码:
- SearchResponse response = client.prepareSearch("wikipedia")
- .setQuery(QueryBuilders.matchAllQuery())
- .addSuggestion(new TermSuggestionBuilder("first_suggestion")
- .text("graphics designer")
- .field("_all"))
- .execute().actionGet();
- for( Entry<? extends Option> entry : response.getSuggest().getSuggestion("first_suggestion").getEntries()) {
- <span style="white-space:pre"> </span>System.out.println("Check for: " + entry.getText() + ". Options:");
- <span style="white-space:pre"> </span>for( Option option : entry.getOptions()) {
- <span style="white-space:pre"> </span>System.out.println("\t" + option.getText());
- <span style="white-space:pre"> </span>}
- }
3.3.12 Counting
- 代码:
- CountResponse response = client.prepareCount("library")
- .setQuery(QueryBuilders.termQuery("title", "elastic"))
- .execute().actionGet();
3.3.13 Scrolling
- 代码:
- SearchResponse responseSearch = client.prepareSearch("library")
- .setScroll("1m")
- .setSearchType(SearchType.SCAN)
- .execute().actionGet();
- String scrollId = responseSearch.getScrollId();
- SearchResponse response = client.prepareSearchScroll(scrollId).execute().actionGet();
3.3.14 Bulk
- 代码:
- BulkResponse response = client.prepareBulk()
- .add(client.prepareIndex("library", "book", "5")
- .setSource("{ \"title\" : \"Solr Cookbook\"}")
- .request())
- .add(client.prepareDelete("library", "book", "2").request()).execute().actionGet();
3.3.15 The delete by query
- 代码:
- DeleteByQueryResponse response = client.prepareDeleteByQuery("library")
- .setQuery(QueryBuilders.termQuery("title", "ElasticSearch"))
- .execute().actionGet();
3.3.16 Multi GET
- 代码:
- MultiGetResponse response = client.prepareMultiGet()
- .add("library", "book", "1", "2")
- .execute().actionGet();
3.3.16 Multi Search
- 代码:
- MultiSearchResponse response = client.prepareMultiSearch()
- .add(client.prepareSearch("library", "book").request())
- .add(client.prepareSearch("news").
- .setFilter(FilterBuilders.termFilter("tags", "important")))
- .execute().actionGet();
3.3.17 Building JSON queries and documents
- 代码:
- IndexResponse response = client
- .prepareIndex("library", "book", "2")
- .setSource("{ \"title\": \"Mastering ElasticSearch\"}")
- .execute().actionGet();
- Map<String, Object> m = Maps.newHashMap();
- m.put("1", "Introduction");
- m.put("2", "Basics");
- m.put("3", "And the rest");
- XContentBuilder json = XContentFactory.jsonBuilder().prettyPrint()
- .startObject()
- .field("id").value("2123")
- .field("lastCommentTime", new Date())
- .nullField("published")
- .field("chapters").map(m)
- .field("title", "Mastering ElasticSearch")
- .array("tags", "search", "ElasticSearch", "nosql")
- .field("values")
- .startArray()
- .value(1)
- .value(10)
- .endArray()
- .endObject();
3.4 The administration API
3.4.1 The cluster administration API
3.4.1.1 The cluster and indices health API
- 代码:
- ClusterHealthResponse response = client.admin().cluster()
- .prepareHealth("library")
- .execute().actionGet();
3.4.1.2 The cluster state API
- 代码:
- ClusterStateResponse response = client.admin().cluster()
- .prepareState()
- .execute().actionGet();
3.4.1.3 The update settings API
- 代码:
- Map<String, Object> map = Maps.newHashMap();
- map.put("indices.ttl.interval", "10m");
- ClusterUpdateSettingsResponse response = client.admin().cluster()
- .prepareUpdateSettings()
- .setTransientSettings(map)
- .execute().actionGet();
3.4.1.4 The reroute API
- 代码:
- ClusterRerouteResponse response = client.admin().cluster()
- .prepareReroute()
- .setDryRun(true)
- .add(new MoveAllocationCommand(new ShardId("library", 3), "G3czOt4HQbKZT1RhpPCULw",PvHtEMuRSJ6rLJ27AW3U6w"),
- new CancelAllocationCommand(new ShardId("library", 2), "G3czOt4HQbKZT1RhpPCULw",rue))
- .execute().actionGet();
3.4.1.5 The nodes information API
- 代码:
- NodesInfoResponse response = client.admin().cluster()
- .prepareNodesInfo()
- .setNetwork(true)
- .setPlugin(true)
- .execute().actionGet();
3.4.1.6 The node statistics API
- 代码:
- NodesStatsResponse response = client.admin().cluster()
- .prepareNodesStats()
- .all()
- .execute().actionGet();
3.4.1.7 The nodes hot threads API
- 代码:
- NodesHotThreadsResponse response = client.admin().cluster()
- .prepareNodesHotThreads()
- .execute().actionGet();
3.4.1.8 The nodes shutdown API
- 代码:
- NodesShutdownResponse response = client.admin().cluster()
- .prepareNodesShutdown()
- .execute().actionGet();
3.4.1.9 The search shards API
- 代码:
- ClusterSearchShardsResponse response = client.admin().cluster()
- .prepareSearchShards()
- .setIndices("library")
- .setRouting("12")
- .execute().actionGet();
3.4.2 The Indices administration API
3.4.2.1 The index existence API
- 代码:
- IndicesExistsResponse response = client.admin().indices()
- .prepareExists("books", "library")
- .execute().actionGet();
3.4.2.2 The Type existence API
- 代码:
- TypesExistsResponse response = client.admin().indices()
- .prepareTypesExists("library")
- .setTypes("book")
- .execute().actionGet();
3.4.2.3 The indices stats API
- 代码:
- IndicesStatsResponse response = client.admin().indices()
- .prepareStats("library")
- .all()
- .execute().actionGet();
3.4.2.4 Index status
- 代码:
- IndicesStatusResponse response = client.admin().indices()
- .prepareStatus("library")
- .setRecovery(true)
- .setSnapshot(true)
- .execute().actionGet();
3.4.2.5 Segments information API
- 代码:
- IndicesSegmentResponse response = client.admin().indices()
- .prepareSegments("library")
- .execute().actionGet();
3.4.2.6 Creating an index API
- 代码:
- CreateIndexResponse response = client.admin().indices()
- .prepareCreate("news")
- .setSettings(ImmutableSettings.settingsBuilder()
- .put("number_of_shards", 1))
- .addMapping("news", XContentFactory.jsonBuilder()
- .startObject()
- .startObject("news")
- .startObject("properties")
- .startObject("title")
- .field("analyzer", "whitespace")
- .field("type", "string")
- .endObject()
- .endObject()
- .endObject()
- .endObject())
- .execute().actionGet();
3.4.2.7 Deleting an index
- 代码:
- DeleteIndexResponse response = client.admin().indices()
- .prepareDelete("news")
- .execute().actionGet();
3.4.2.8 Closing an index
- 代码:
- CloseIndexResponse response = client.admin().indices()
- .prepareClose("library")
- .execute().actionGet();
3.4.2.9 Opening an index
- 代码:
- OpenIndexResponse response = client.admin().indices()
- .prepareOpen("library")
- .execute().actionGet();
3.4.2.10 The Refresh API
- 代码:
- RefreshResponse response = client.admin().indices()
- .prepareRefresh("library")
- .execute().actionGet();
3.4.2.11 The Flush API
- 代码:
- FlushResponse response = client.admin().indices()
- .prepareFlush("library")
- .setFull(false)
- .execute().actionGet();
3.4.2.12 The Optimize API
- 代码:
- OptimizeResponse response = client.admin().indices()
- .prepareOptimize("library")
- .setMaxNumSegments(2)
- .setFlush(true)
- .setOnlyExpungeDeletes(false)
- .execute().actionGet();
3.4.2.13 The put mapping API
- 代码:
- PutMappingResponse response = client.admin().indices()
- .preparePutMapping("news")
- .setType("news")
- .setSource(XContentFactory.jsonBuilder()
- .startObject()
- .startObject("news")
- .startObject("properties")
- .startObject("title")
- .field("analyzer", "whitespace")
- .field("type", "string")
- .endObject()
- .endObject()
- .endObject()
- .endObject())
- .execute().actionGet();
3.4.2.14 The delete mapping API
- 代码:
- DeleteMappingResponse response = client.admin().indices()
- .prepareDeleteMapping("news")
- .setType("news")
- .execute().actionGet();
3.4.2.15 The gateway snapshot API
- 代码:
- GatewaySnapshotResponse response = client.admin().indices()
- .prepareGatewaySnapshot("news")
- .execute().actionGet();
3.4.2.16 The aliases API
- 代码:
- IndicesAliasesResponse response = client.admin().indices()
- .prepareAliases()
- .addAlias("news", "n")
- .addAlias("library", "elastic_books",
- FilterBuilders.termFilter("title", "elasticsearch"))
- .removeAlias("news", "current_news")
- .execute().actionGet();
3.4.2.17 The get aliases API
- 代码:
- IndicesGetAliasesResponse response = client.admin().indices()
- .prepareGetAliases("elastic_books", "n")
- .execute().actionGet();
3.4.2.18 The aliases exists API
- 代码:
- AliasesExistResponse response = client.admin().indices()
- .prepareAliasesExist("elastic*", "unknown")
- .execute().actionGet();
3.4.2.19 The clear cache API
- 代码:
- ClearIndicesCacheResponse response = client.admin().indices()
- .prepareClearCache("library")
- .setFieldDataCache(true)
- .setFields("title")
- .setFilterCache(true)
- .setIdCache(true)
- .execute().actionGet();
3.4.2.20 The update settings API
- 代码:
- UpdateSettingsResponse response = client.admin().indices()
- .prepareUpdateSettings("library")
- .setSettings(ImmutableSettings.builder()
- .put("index.number_of_replicas", 2))
- .execute().actionGet();
3.4.2.21 The analyze API
- 代码:
- AnalyzeResponse response = client.admin().indices()
- .prepareAnalyze("library", "ElasticSearch Servers")
- .setTokenizer("whitespace")
- .setTokenFilters("nGram")
- .execute().actionGet();
3.4.2.22 The put template API
- 代码:
- PutIndexTemplateResponse response = client.admin().indices()
- .preparePutTemplate("my_template")
- .setTemplate("product*")
- .setSettings(ImmutableSettings.builder()
- .put("index.number_of_replicas", 2)
- .put("index.number_of_shards", 1))
- .addMapping("item", XContentFactory.jsonBuilder()
- .startObject()
- .startObject("item")
- .startObject("properties")
- .startObject("title")
- .field("type", "string")
- .endObject()
- .endObject()
- .endObject()
- .endObject())
- .execute().actionGet();
3.4.2.23 The delete template API
- 代码:
- DeleteIndexTemplateResponse response = client.admin().indices()
- .prepareDeleteTemplate("my_*")
- .execute().actionGet();
3.4.2.24 The validate query API
- 代码:
- ValidateQueryResponse response = client.admin().indices()
- .prepareValidateQuery("library")
- .setExplain(true)
- .setQuery(XContentFactory.jsonBuilder()
- .startObject()
- .field("name").value("elastic search")
- .endObject().bytes())
- .execute().actionGet();
3.4.2.25 The put warmer API
- 代码:
- PutWarmerResponse response = client.admin().indices()
- .preparePutWarmer("library_warmer")
- .setSearchRequest(client.prepareSearch("library")
- .addFacet(FacetBuilders
- .termsFacet("tags").field("tags")))
- .execute().actionGet();
3.4.2.26 The delete warmer API
- 代码:
- DeleteWarmerResponse response = client.admin().indices()
- .prepareDeleteWarmer()
- .setName("library_*")
- .execute().actionGet();
elasticsearch Java API汇总的更多相关文章
- [搜索]ElasticSearch Java Api(一) -添加数据创建索引
转载:http://blog.csdn.net/napoay/article/details/51707023 ElasticSearch JAVA API官网文档:https://www.elast ...
- Elasticsearch java api 基本搜索部分详解
文档是结合几个博客整理出来的,内容大部分为转载内容.在使用过程中,对一些疑问点进行了整理与解析. Elasticsearch java api 基本搜索部分详解 ElasticSearch 常用的查询 ...
- Elasticsearch java api 常用查询方法QueryBuilder构造举例
转载:http://m.blog.csdn.net/u012546526/article/details/74184769 Elasticsearch java api 常用查询方法QueryBuil ...
- 第08章 ElasticSearch Java API
本章内容 使用客户端对象(client object)连接到本地或远程ElasticSearch集群. 逐条或批量索引文档. 更新文档内容. 使用各种ElasticSearch支持的查询方式. 处理E ...
- Elasticsearch Java API深入详解
0.题记 之前Elasticsearch的应用比较多,但大多集中在关系型.非关系型数据库与Elasticsearch之间的同步.以上内容完成了Elasticsearch所需要的基础数据量的供给.但想要 ...
- Elasticsearch Java API 很全的整理
Elasticsearch 的API 分为 REST Client API(http请求形式)以及 transportClient API两种.相比来说transportClient API效率更高, ...
- ElasticSearch Java api 详解_V1.0
/×××××××××××××××××××××××××××××××××××××××××/ Author:xxx0624 HomePage:http://www.cnblogs.com/xxx0624/ ...
- Elasticsearch JAVA api搞定groupBy聚合
本文给出如何使用Elasticsearch的Java API做类似SQL的group by聚合.为了简单起见,只给出一级groupby即group by field1(而不涉及到多级,例如group ...
- Elasticsearch JAVA api轻松搞定groupBy聚合
本文给出如何使用Elasticsearch的Java API做类似SQL的group by聚合. 为了简单起见,只给出一级groupby即group by field1(而不涉及到多级,例如group ...
随机推荐
- Maven学习5-聚合与继承
一.聚合 如果我们想一次构建多个项目模块,那我们就需要对多个项目模块进行聚合 1.1.聚合配置代码 1 <modules> 2 <module>模块一</module&g ...
- Windows环境下使用Redis缓存工具的图文详细方法
一.简介 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合)和zset(有序集合). ...
- nova boot instance call flow
参考http://www.cnblogs.com/popsuper1982/p/3927390.html
- SQL语句统计每天、每月、每年的 数据
SQL语句统计每天.每月.每年的数据 1.每年select year(ordertime) 年,sum(Total) 销售合计from 订单表group by year(ordertime) 2.每月 ...
- TIOBE Index for December 2015(转载)
There is hardly any doubt about it, Java will become TIOBE's programming language of the year 2015. ...
- HBase使用场景和成功案例 (转)
HBase 使用场景和成功案例 有时候了解软件产品的最好方法是看看它是怎么用的.它可以解决什么问题和这些解决方案如何适用于大型应用架构,能够告诉你很多.因为HBase有许多公开的产品部署,我们正好可以 ...
- ADF_Desktop Integration系列2_ADF桌面集成入门之开发简单ADF Desktop Excel
2013-05-01 Created By BaoXinjian
- [HTML] CSS3 文本效果
CSS3 文本效果 CSS3中包含几个新的文本特征. 在本章中您将了解以下文本属性: text-shadow word-wrap 浏览器支持
- CRM 2016 js 奇怪现象
假如 js 中如果定义了 两个字段的onchage 事件. 如果一个字段的onchange事件,改变了另一个字段的值,那么也会触发另一个字段的onchange事件!!!!????
- 课堂笔记--Strom并发模型
Strom并发模型: topology是如何运行的?(可与mapreduce对比) 第一层:cluster 第二层:supervisor(host.node.机 ...