`
weitao1026
  • 浏览: 1047772 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Elasticsearch Java API总汇

 
阅读更多

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

  1. 复制代码
    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();
分享到:
评论

相关推荐

    es7db:Elasticsearch 7 API的Java包装器

    Elasticsearch 7数据库Elasticsearch 7 API的简单Java实现Java 8+。 可通过外部.properties文件轻松配置。 简单的界面,可批量或批量管理文档创建/删除/更新。 丰富且适应性强的查询创建。 灵活且易于使用的“通用...

    项目实战——Spark将Hive表的数据写入ElasticSearch(Java版本)

    在本项目实战中,我们将探讨如何使用Java编程语言,结合Spark和Hive,将Hive中的数据高效地导入到ElasticSearch(ES)中,并利用ES的别名机制实现数据更新的平滑过渡。以下是对这个流程的详细解析: 1. **Hive数据...

    Elasticsearch1.x Java教程

    - **增删改查(CRUD)**:这部分内容介绍了如何通过Elasticsearch 的Java API执行基本的数据管理操作。 - **数据模型**:概述了Elasticsearch 中的数据存储模型,包括文档、索引等核心概念。 - **工具类**:介绍了...

    一个elasticsearch的示例代码

    Elasticsearch是一个分布式、RESTful风格的搜索和数据分析引擎,被广泛用于实时的索引和搜索,尤其在大数据分析领域有着显著的...同时,这也能帮助你了解Elasticsearch的API使用方式以及如何在Java中构建RESTful请求。

    ElasticSearch入门到精通(基于ELK技术栈ElasticSearch7.8.版本).rar

    在 ELK 技术栈(Elasticsearch, Logstash, Kibana)中,Elasticsearch 负责存储和索引日志数据,SpringBoot 是一个流行的 Java 应用开发框架,它们经常一起用于企业级的日志管理和分析系统。 **1. Elasticsearch ...

    最新版windows elasticsearch-8.3.1-windows-x86_64.zip

    9. **聚合分析**:除了搜索,Elasticsearch还支持聚合分析,可以进行数据汇总、统计和分组,非常适合数据分析和报表生成。 10. **监控与可视化**:Kibana是Elasticsearch的数据可视化工具,可以展示集群状态、搜索...

    elasticsearch-1.7.1.tar.gz

    3. **RESTful API**:Elasticsearch 使用简单易用的 RESTful API 进行操作,如增删改查,这使得它易于集成到各种开发环境中。 4. **JSON 文档存储**:Elasticsearch 存储的数据是 JSON 格式,这是一种轻量级的、...

    elasticsearch-中文开发指南

    - **ES vs Solr:** 对比分析 Elasticsearch 与 Apache Solr 的异同点。 - **Elasticsearch River JDBC:** 描述如何使用 JDBC 连接器将关系型数据库中的数据流式导入 Elasticsearch。 #### 结论 Elasticsearch 作为...

    最详细的Elasticsearch学习资料(源码)

    Elasticsearch 是用 Java 语言编写的,并且提供了 RESTful API 以及丰富的客户端库,能够方便地与其它应用集成。 Elasticsearch 具有以下主要特点: 全文搜索:Elasticsearch 提供了快速、灵活、准确的全文搜索...

    elasticSearch 2.4.4

    通过 Spring Data Elasticsearch,可以轻松地将这个功能强大的搜索引擎整合到 Java 应用程序中。在使用时,理解其分布式特性、索引机制以及查询语法等核心概念,将有助于更好地利用 Elasticsearch 提供的服务。

    elasticsearch

    Elasticsearch(简称ES)是一款基于Lucene的开源全文搜索引擎,它以其分布式、实时、高可扩展性以及强大的分析能力而受到广泛赞誉。在现代大数据环境中,Elasticsearch常用于日志分析、实时监控、数据搜索等场景。 ...

    Elasticsearch最新面试题,2023年面试题及答案汇总.txt

    ### 16、REST API在 Elasticsearch 方面有哪些优势? ### 17、请解释一下 Elasticsearch 中聚合? ### 18、什么是ElasticSearch索引? ### 19、ElasticSearch如何避免脑裂? ### 20、Elasticsearch 支持哪些配置管理...

    elasticsearch-6.5.4搜索引擎

    Elasticsearch 采用 RESTful 风格的 API 进行通信,这使得与 Elasticsearch 的交互变得简单直观。REST(Representational State Transfer)是一种网络应用程序的设计风格和开发方式,基于 HTTP 协议,通过 GET、POST...

    八股文知识点汇总——各互联网大厂java工程师面试题.pdf

    - Elasticsearch是分布式搜索引擎,考察索引、查询优化、集群管理等内容。 - Memcached是内存缓存系统,了解其基本原理、操作命令和使用场景。 - RabbitMQ和Kafka是消息中间件,关注队列、主题、消费模式等。 - ...

    2021最新Java面试题合集.zip

    - **RESTful API**:使用HTTP操作Elasticsearch。 - **Lucene**:Elasticsearch的核心库,用于全文检索。 以上内容涵盖了Java开发者在面试中可能遇到的主要知识点,学习并理解这些内容将有助于提升你的技术水平和...

    ES分布式搜索解决方案.docx

    - **Solr**:基于Java的Web应用,提供RESTful API,相比Lucene更易用,但可能不如Elasticsearch灵活。 - **Elastic Stack**:包括Logstash、Kibana等组件,形成完整的数据收集、分析和可视化解决方案。 总的来说,...

    ES学习资料干干干干刚馕

    标题 "ES学习资料干干干干刚馕" 暗示了这是一份关于Elasticsearch(简称ES)的学习资源集合。Elasticsearch是一个开源的全文搜索引擎,常用于大数据分析和实时搜索应用。它基于Lucene库构建,提供了一个分布式、...

    汇总java生态圈常用技术框架、开源中间件,系统架构、数据库、大公司架构案例

    例如,使用Spring Cloud进行服务治理,通过Hystrix实现服务降级和熔断,利用Ribbon进行客户端负载均衡,使用Zipkin或Sleuth进行分布式追踪,以及Elasticsearch、Kibana、Logstash组成的ELK日志分析栈,这些都是构建...

Global site tag (gtag.js) - Google Analytics