http://blog.csdn.net/changong28/article/details/38445805#comments

3.1 集群的连接

3.1.1 作为Elasticsearch节点

  1. 代码:
  2. import static org.elasticsearch.node.NodeBuilder.nodeBuilder;
  3. import org.elasticsearch.client.Client;
  4. import org.elasticsearch.node.Node;
  5. Node node = nodeBuilder().clusterName("escluster2").client(true).
  6. node();
  7. Client client = node.client();

3.1.2 使用Transport连接

  1. 代码:
  2. import org.elasticsearch.client.transport.TransportClient;
  3. import org.elasticsearch.common.settings.ImmutableSettings;
  4. import org.elasticsearch.common.settings.Settings;
  5. import org.elasticsearch.common.transport.InetSocketTransportAddress;
  6. Settings settings = ImmutableSettings.settingsBuilder().put("cluster.name", "escluster2").build();
  7. TransportClient client = new TransportClient(settings);
  8. client.addTransportAddress(new InetSocketTransportAddress("127.0.0.1",9300));

3.2 文档的CRUD

3.2.1 查询文档

  1. 代码:
  2. GetResponse response = client.prepareGet("library", "book", "1")
  3. .setFields("title", "_source")
  4. .execute().actionGet();

3.2.2 索引文档

  1. 代码:
  2. import org.elasticsearch.action.index.IndexResponse;
  3. import org.elasticsearch.client.Client;
  4. IndexResponse response = client.prepareIndex("library", "book", "2")
  5. .setSource("{ \"title\": \"Mastering ElasticSearch\"}")
  6. .execute().actionGet();

3.2.3 更新文档

  1. 代码:
  2. import org.elasticsearch.action.update.UpdateResponse;
  3. import org.elasticsearch.client.Client;
  4. import java.util.Map;
  5. import org.elasticsearch.common.collect.Maps;
  6. Map<String, Object> params = Maps.newHashMap();
  7. params.put("ntitle", "ElasticSearch Server Book");
  8. UpdateResponse response = client.prepareUpdate("library", "book", "2")
  9. .setScript("ctx._source.title = ntitle")
  10. .setScriptParams(params)
  11. .execute().actionGet();

3.2.4 删除文档

  1. 代码:
  2. import org.elasticsearch.action.delete.DeleteResponse;
  3. import org.elasticsearch.client.Client;
  4. DeleteResponse response = client.prepareDelete("library", "book", "2")
  5. .execute().actionGet();

3.3 Elasticsearch检索

3.3.1 Preparing a query

  1. 代码:
  2. import org.elasticsearch.action.search.SearchResponse;
  3. import org.elasticsearch.client.Client;
  4. import org.elasticsearch.search.SearchHit;
  5. SearchResponse response = client.prepareSearch("library")
  6. .addFields("title", "_source")
  7. .execute().actionGet();
  8. for(SearchHit hit: response.getHits().getHits()) {
  9. <span style="white-space:pre">    </span>System.out.println(hit.getId());
  10. <span style="white-space:pre">    </span>if (hit.getFields().containsKey("title")) {
  11. <span style="white-space:pre">        </span>System.out.println("field.title: "+ hit.getFields().get("title").getValue());
  12. <span style="white-space:pre">    </span>}
  13. <span style="white-space:pre">    </span>System.out.println("source.title: " + hit.getSource().get("title"));
  14. }

3.3.2 Building queries

  1. 代码:
  2. import org.elasticsearch.index.query.QueryBuilder;
  3. import org.elasticsearch.index.query.QueryBuilders;
  4. QueryBuilder queryBuilder = QueryBuilders
  5. .disMaxQuery()
  6. .add(QueryBuilders.termQuery("title", "Elastic"))
  7. .add(QueryBuilders.prefixQuery("title", "el"));
  8. System.out.println(queryBuilder.toString());
  9. SearchResponse response = client.prepareSearch("library")
  10. .setQuery(queryBuilder)
  11. .execute().actionGet();

3.3.3 Using the match all documents query

  1. 代码:
  2. queryBuilder = QueryBuilders.matchAllQuery()
  3. .boost(11f).normsField("title");

3.3.4 The match query

  1. 代码:
  2. queryBuilder = QueryBuilders
  3. .matchQuery("message", "a quick brown fox")
  4. .operator(Operator.AND)
  5. .zeroTermsQuery(ZeroTermsQuery.ALL);

3.3.5 Using the geo shape query

  1. 代码:
  2. queryBuilder = QueryBuilders.geoShapeQuery("location",
  3. ShapeBuilder.newRectangle()
  4. .topLeft(13, 53)
  5. .bottomRight(14, 52)
  6. .build());

3.3.6 Paging query

  1. 代码:
  2. SearchResponse response = client.prepareSearch("library")
  3. .setQuery(QueryBuilders.matchAllQuery())
  4. .setFrom(10)
  5. .setSize(20)
  6. .execute().actionGet();

3.3.7 Sorting

  1. 代码:
  2. SearchResponse response = client.prepareSearch("library")
  3. .setQuery(QueryBuilders.matchAllQuery())
  4. .addSort(SortBuilders.fieldSort("title"))
  5. .addSort("_score", SortOrder.DESC)
  6. .execute().actionGet()

3.3.8 Filtering

  1. 代码:
  2. FilterBuilder filterBuilder = FilterBuilders
  3. .andFilter(
  4. FilterBuilders.existsFilter("title").filterName("exist"),
  5. FilterBuilders.termFilter("title", "elastic")
  6. );
  7. SearchResponse response = client.prepareSearch("library")
  8. .setFilter(filterBuilder)
  9. .execute().actionGet();

3.3.9 Faceting

  1. 代码:
  2. FacetBuilder facetBuilder = FacetBuilders
  3. .filterFacet("test")
  4. .filter(FilterBuilders.termFilter("title", "elastic"));
  5. SearchResponse response = client.prepareSearch("library")
  6. .addFacet(facetBuilder)
  7. .execute().actionGet();

3.3.10 Highlighting

  1. 代码:
  2. SearchResponse response = client.prepareSearch("wikipedia")
  3. .addHighlightedField("title")
  4. .setQuery(QueryBuilders.termQuery("title", "actress"))
  5. .setHighlighterPreTags("<1>", "<2>")
  6. .setHighlighterPostTags("</1>", "</2>")
  7. .execute().actionGet();
  8. for(SearchHit hit: response.getHits().getHits()) {
  9. <span style="white-space:pre">    </span>HighlightField hField = hit.getHighlightFields().get("title");
  10. <span style="white-space:pre">    </span>for (Text t : hField.fragments()) {
  11. <span style="white-space:pre">        </span>System.out.println(t.string());
  12. <span style="white-space:pre">    </span>}
  13. }

3.3.11 Suggestions

  1. 代码:
  2. SearchResponse response = client.prepareSearch("wikipedia")
  3. .setQuery(QueryBuilders.matchAllQuery())
  4. .addSuggestion(new TermSuggestionBuilder("first_suggestion")
  5. .text("graphics designer")
  6. .field("_all"))
  7. .execute().actionGet();
  8. for( Entry<? extends Option> entry : response.getSuggest().getSuggestion("first_suggestion").getEntries()) {
  9. <span style="white-space:pre">    </span>System.out.println("Check for: " + entry.getText() + ". Options:");
  10. <span style="white-space:pre">    </span>for( Option option : entry.getOptions()) {
  11. <span style="white-space:pre">        </span>System.out.println("\t" + option.getText());
  12. <span style="white-space:pre">    </span>}
  13. }

3.3.12 Counting

  1. 代码:
  2. CountResponse response = client.prepareCount("library")
  3. .setQuery(QueryBuilders.termQuery("title", "elastic"))
  4. .execute().actionGet();

3.3.13 Scrolling

  1. 代码:
  2. SearchResponse responseSearch = client.prepareSearch("library")
  3. .setScroll("1m")
  4. .setSearchType(SearchType.SCAN)
  5. .execute().actionGet();
  6. String scrollId = responseSearch.getScrollId();
  7. SearchResponse response = client.prepareSearchScroll(scrollId).execute().actionGet();

3.3.14 Bulk

  1. 代码:
  2. BulkResponse response = client.prepareBulk()
  3. .add(client.prepareIndex("library", "book", "5")
  4. .setSource("{ \"title\" : \"Solr Cookbook\"}")
  5. .request())
  6. .add(client.prepareDelete("library", "book", "2").request()).execute().actionGet();

3.3.15 The delete by query

  1. 代码:
  2. DeleteByQueryResponse response = client.prepareDeleteByQuery("library")
  3. .setQuery(QueryBuilders.termQuery("title", "ElasticSearch"))
  4. .execute().actionGet();

3.3.16 Multi GET

  1. 代码:
  2. MultiGetResponse response = client.prepareMultiGet()
  3. .add("library", "book", "1", "2")
  4. .execute().actionGet();

3.3.16 Multi Search

  1. 代码:
  2. MultiSearchResponse response = client.prepareMultiSearch()
  3. .add(client.prepareSearch("library", "book").request())
  4. .add(client.prepareSearch("news").
  5. .setFilter(FilterBuilders.termFilter("tags", "important")))
  6. .execute().actionGet();

3.3.17 Building JSON queries and documents

  1. 代码:
  2. IndexResponse response = client
  3. .prepareIndex("library", "book", "2")
  4. .setSource("{ \"title\": \"Mastering ElasticSearch\"}")
  5. .execute().actionGet();
  6. Map<String, Object> m = Maps.newHashMap();
  7. m.put("1", "Introduction");
  8. m.put("2", "Basics");
  9. m.put("3", "And the rest");
  10. XContentBuilder json = XContentFactory.jsonBuilder().prettyPrint()
  11. .startObject()
  12. .field("id").value("2123")
  13. .field("lastCommentTime", new Date())
  14. .nullField("published")
  15. .field("chapters").map(m)
  16. .field("title", "Mastering ElasticSearch")
  17. .array("tags", "search", "ElasticSearch", "nosql")
  18. .field("values")
  19. .startArray()
  20. .value(1)
  21. .value(10)
  22. .endArray()
  23. .endObject();

3.4 The administration API

3.4.1 The cluster administration API

3.4.1.1 The cluster and indices health API

  1. 代码:
  2. ClusterHealthResponse response = client.admin().cluster()
  3. .prepareHealth("library")
  4. .execute().actionGet();

3.4.1.2 The cluster state API

  1. 代码:
  2. ClusterStateResponse response = client.admin().cluster()
  3. .prepareState()
  4. .execute().actionGet();

3.4.1.3 The update settings API

  1. 代码:
  2. Map<String, Object> map = Maps.newHashMap();
  3. map.put("indices.ttl.interval", "10m");
  4. ClusterUpdateSettingsResponse response = client.admin().cluster()
  5. .prepareUpdateSettings()
  6. .setTransientSettings(map)
  7. .execute().actionGet();

3.4.1.4 The reroute API

  1. 代码:
  2. ClusterRerouteResponse response = client.admin().cluster()
  3. .prepareReroute()
  4. .setDryRun(true)
  5. .add(new MoveAllocationCommand(new ShardId("library", 3), "G3czOt4HQbKZT1RhpPCULw",PvHtEMuRSJ6rLJ27AW3U6w"),
  6. new CancelAllocationCommand(new ShardId("library", 2), "G3czOt4HQbKZT1RhpPCULw",rue))
  7. .execute().actionGet();

3.4.1.5 The nodes information API

  1. 代码:
  2. NodesInfoResponse response = client.admin().cluster()
  3. .prepareNodesInfo()
  4. .setNetwork(true)
  5. .setPlugin(true)
  6. .execute().actionGet();

3.4.1.6 The node statistics API

  1. 代码:
  2. NodesStatsResponse response = client.admin().cluster()
  3. .prepareNodesStats()
  4. .all()
  5. .execute().actionGet();

3.4.1.7 The nodes hot threads API

  1. 代码:
  2. NodesHotThreadsResponse response = client.admin().cluster()
  3. .prepareNodesHotThreads()
  4. .execute().actionGet();

3.4.1.8 The nodes shutdown API

  1. 代码:
  2. NodesShutdownResponse response = client.admin().cluster()
  3. .prepareNodesShutdown()
  4. .execute().actionGet();

3.4.1.9 The search shards API

  1. 代码:
  2. ClusterSearchShardsResponse response = client.admin().cluster()
  3. .prepareSearchShards()
  4. .setIndices("library")
  5. .setRouting("12")
  6. .execute().actionGet();

3.4.2 The Indices administration API

3.4.2.1 The index existence API

  1. 代码:
  2. IndicesExistsResponse response = client.admin().indices()
  3. .prepareExists("books", "library")
  4. .execute().actionGet();

3.4.2.2 The Type existence API

  1. 代码:
  2. TypesExistsResponse response = client.admin().indices()
  3. .prepareTypesExists("library")
  4. .setTypes("book")
  5. .execute().actionGet();

3.4.2.3 The indices stats API

  1. 代码:
  2. IndicesStatsResponse response = client.admin().indices()
  3. .prepareStats("library")
  4. .all()
  5. .execute().actionGet();

3.4.2.4 Index status

  1. 代码:
  2. IndicesStatusResponse response = client.admin().indices()
  3. .prepareStatus("library")
  4. .setRecovery(true)
  5. .setSnapshot(true)
  6. .execute().actionGet();

3.4.2.5 Segments information API

  1. 代码:
  2. IndicesSegmentResponse response = client.admin().indices()
  3. .prepareSegments("library")
  4. .execute().actionGet();

3.4.2.6 Creating an index API

  1. 代码:
  2. CreateIndexResponse response = client.admin().indices()
  3. .prepareCreate("news")
  4. .setSettings(ImmutableSettings.settingsBuilder()
  5. .put("number_of_shards", 1))
  6. .addMapping("news", XContentFactory.jsonBuilder()
  7. .startObject()
  8. .startObject("news")
  9. .startObject("properties")
  10. .startObject("title")
  11. .field("analyzer", "whitespace")
  12. .field("type", "string")
  13. .endObject()
  14. .endObject()
  15. .endObject()
  16. .endObject())
  17. .execute().actionGet();

3.4.2.7 Deleting an index

  1. 代码:
  2. DeleteIndexResponse response = client.admin().indices()
  3. .prepareDelete("news")
  4. .execute().actionGet();

3.4.2.8 Closing an index

  1. 代码:
  2. CloseIndexResponse response = client.admin().indices()
  3. .prepareClose("library")
  4. .execute().actionGet();

3.4.2.9 Opening an index

  1. 代码:
  2. OpenIndexResponse response = client.admin().indices()
  3. .prepareOpen("library")
  4. .execute().actionGet();

3.4.2.10 The Refresh API

  1. 代码:
  2. RefreshResponse response = client.admin().indices()
  3. .prepareRefresh("library")
  4. .execute().actionGet();

3.4.2.11 The Flush API

  1. 代码:
  2. FlushResponse response = client.admin().indices()
  3. .prepareFlush("library")
  4. .setFull(false)
  5. .execute().actionGet();

3.4.2.12 The Optimize API

  1. 代码:
  2. OptimizeResponse response = client.admin().indices()
  3. .prepareOptimize("library")
  4. .setMaxNumSegments(2)
  5. .setFlush(true)
  6. .setOnlyExpungeDeletes(false)
  7. .execute().actionGet();

3.4.2.13 The put mapping API

  1. 代码:
  2. PutMappingResponse response = client.admin().indices()
  3. .preparePutMapping("news")
  4. .setType("news")
  5. .setSource(XContentFactory.jsonBuilder()
  6. .startObject()
  7. .startObject("news")
  8. .startObject("properties")
  9. .startObject("title")
  10. .field("analyzer", "whitespace")
  11. .field("type", "string")
  12. .endObject()
  13. .endObject()
  14. .endObject()
  15. .endObject())
  16. .execute().actionGet();

3.4.2.14 The delete mapping API

  1. 代码:
  2. DeleteMappingResponse response = client.admin().indices()
  3. .prepareDeleteMapping("news")
  4. .setType("news")
  5. .execute().actionGet();

3.4.2.15 The gateway snapshot API

  1. 代码:
  2. GatewaySnapshotResponse response = client.admin().indices()
  3. .prepareGatewaySnapshot("news")
  4. .execute().actionGet();

3.4.2.16 The aliases API

  1. 代码:
  2. IndicesAliasesResponse response = client.admin().indices()
  3. .prepareAliases()
  4. .addAlias("news", "n")
  5. .addAlias("library", "elastic_books",
  6. FilterBuilders.termFilter("title", "elasticsearch"))
  7. .removeAlias("news", "current_news")
  8. .execute().actionGet();

3.4.2.17 The get aliases API

  1. 代码:
  2. IndicesGetAliasesResponse response = client.admin().indices()
  3. .prepareGetAliases("elastic_books", "n")
  4. .execute().actionGet();

3.4.2.18 The aliases exists API

  1. 代码:
  2. AliasesExistResponse response = client.admin().indices()
  3. .prepareAliasesExist("elastic*", "unknown")
  4. .execute().actionGet();

3.4.2.19 The clear cache API

  1. 代码:
  2. ClearIndicesCacheResponse response = client.admin().indices()
  3. .prepareClearCache("library")
  4. .setFieldDataCache(true)
  5. .setFields("title")
  6. .setFilterCache(true)
  7. .setIdCache(true)
  8. .execute().actionGet();

3.4.2.20 The update settings API

  1. 代码:
  2. UpdateSettingsResponse response = client.admin().indices()
  3. .prepareUpdateSettings("library")
  4. .setSettings(ImmutableSettings.builder()
  5. .put("index.number_of_replicas", 2))
  6. .execute().actionGet();

3.4.2.21 The analyze API

  1. 代码:
  2. AnalyzeResponse response = client.admin().indices()
  3. .prepareAnalyze("library", "ElasticSearch Servers")
  4. .setTokenizer("whitespace")
  5. .setTokenFilters("nGram")
  6. .execute().actionGet();

3.4.2.22 The put template API

  1. 代码:
  2. PutIndexTemplateResponse response = client.admin().indices()
  3. .preparePutTemplate("my_template")
  4. .setTemplate("product*")
  5. .setSettings(ImmutableSettings.builder()
  6. .put("index.number_of_replicas", 2)
  7. .put("index.number_of_shards", 1))
  8. .addMapping("item", XContentFactory.jsonBuilder()
  9. .startObject()
  10. .startObject("item")
  11. .startObject("properties")
  12. .startObject("title")
  13. .field("type", "string")
  14. .endObject()
  15. .endObject()
  16. .endObject()
  17. .endObject())
  18. .execute().actionGet();

3.4.2.23 The delete template API

  1. 代码:
  2. DeleteIndexTemplateResponse response = client.admin().indices()
  3. .prepareDeleteTemplate("my_*")
  4. .execute().actionGet();

3.4.2.24 The validate query API

  1. 代码:
  2. ValidateQueryResponse response = client.admin().indices()
  3. .prepareValidateQuery("library")
  4. .setExplain(true)
  5. .setQuery(XContentFactory.jsonBuilder()
  6. .startObject()
  7. .field("name").value("elastic search")
  8. .endObject().bytes())
  9. .execute().actionGet();

3.4.2.25 The put warmer API

  1. 代码:
  2. PutWarmerResponse response = client.admin().indices()
  3. .preparePutWarmer("library_warmer")
  4. .setSearchRequest(client.prepareSearch("library")
  5. .addFacet(FacetBuilders
  6. .termsFacet("tags").field("tags")))
  7. .execute().actionGet();

3.4.2.26 The delete warmer API

    1. 代码:
    2. DeleteWarmerResponse response = client.admin().indices()
    3. .prepareDeleteWarmer()
    4. .setName("library_*")
    5. .execute().actionGet();

elasticsearch Java API汇总的更多相关文章

  1. [搜索]ElasticSearch Java Api(一) -添加数据创建索引

    转载:http://blog.csdn.net/napoay/article/details/51707023 ElasticSearch JAVA API官网文档:https://www.elast ...

  2. Elasticsearch java api 基本搜索部分详解

    文档是结合几个博客整理出来的,内容大部分为转载内容.在使用过程中,对一些疑问点进行了整理与解析. Elasticsearch java api 基本搜索部分详解 ElasticSearch 常用的查询 ...

  3. Elasticsearch java api 常用查询方法QueryBuilder构造举例

    转载:http://m.blog.csdn.net/u012546526/article/details/74184769 Elasticsearch java api 常用查询方法QueryBuil ...

  4. 第08章 ElasticSearch Java API

    本章内容 使用客户端对象(client object)连接到本地或远程ElasticSearch集群. 逐条或批量索引文档. 更新文档内容. 使用各种ElasticSearch支持的查询方式. 处理E ...

  5. Elasticsearch Java API深入详解

    0.题记 之前Elasticsearch的应用比较多,但大多集中在关系型.非关系型数据库与Elasticsearch之间的同步.以上内容完成了Elasticsearch所需要的基础数据量的供给.但想要 ...

  6. Elasticsearch Java API 很全的整理

    Elasticsearch 的API 分为 REST Client API(http请求形式)以及 transportClient API两种.相比来说transportClient API效率更高, ...

  7. ElasticSearch Java api 详解_V1.0

    /×××××××××××××××××××××××××××××××××××××××××/ Author:xxx0624 HomePage:http://www.cnblogs.com/xxx0624/ ...

  8. Elasticsearch JAVA api搞定groupBy聚合

    本文给出如何使用Elasticsearch的Java API做类似SQL的group by聚合.为了简单起见,只给出一级groupby即group by field1(而不涉及到多级,例如group ...

  9. Elasticsearch JAVA api轻松搞定groupBy聚合

    本文给出如何使用Elasticsearch的Java API做类似SQL的group by聚合. 为了简单起见,只给出一级groupby即group by field1(而不涉及到多级,例如group ...

随机推荐

  1. Maven学习5-聚合与继承

    一.聚合 如果我们想一次构建多个项目模块,那我们就需要对多个项目模块进行聚合 1.1.聚合配置代码 1 <modules> 2 <module>模块一</module&g ...

  2. Windows环境下使用Redis缓存工具的图文详细方法

    一.简介 redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合)和zset(有序集合). ...

  3. nova boot instance call flow

    参考http://www.cnblogs.com/popsuper1982/p/3927390.html

  4. SQL语句统计每天、每月、每年的 数据

    SQL语句统计每天.每月.每年的数据 1.每年select year(ordertime) 年,sum(Total) 销售合计from 订单表group by year(ordertime) 2.每月 ...

  5. TIOBE Index for December 2015(转载)

    There is hardly any doubt about it, Java will become TIOBE's programming language of the year 2015. ...

  6. HBase使用场景和成功案例 (转)

    HBase 使用场景和成功案例 有时候了解软件产品的最好方法是看看它是怎么用的.它可以解决什么问题和这些解决方案如何适用于大型应用架构,能够告诉你很多.因为HBase有许多公开的产品部署,我们正好可以 ...

  7. ADF_Desktop Integration系列2_ADF桌面集成入门之开发简单ADF Desktop Excel

    2013-05-01 Created By BaoXinjian

  8. [HTML] CSS3 文本效果

    CSS3 文本效果 CSS3中包含几个新的文本特征. 在本章中您将了解以下文本属性: text-shadow word-wrap 浏览器支持

  9. CRM 2016 js 奇怪现象

    假如 js 中如果定义了 两个字段的onchage 事件. 如果一个字段的onchange事件,改变了另一个字段的值,那么也会触发另一个字段的onchange事件!!!!????

  10. 课堂笔记--Strom并发模型

    Strom并发模型:     topology是如何运行的?(可与mapreduce对比)         第一层:cluster         第二层:supervisor(host.node.机 ...