`

elasticsearch API

es 
阅读更多
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();
分享到:
评论

相关推荐

    esapi-2.1.0.1.zip(esapi-2.1.0.1.jar)

    ESAPI,全称为“Enterprise Security API”,是一款开源的安全软件开发框架,主要针对Java平台。它由OWASP(开放网络应用安全项目)维护,旨在提供一套全面的、易于使用的安全编程接口,帮助开发者在构建应用程序时...

    esapi-2.1.0.1_esapi-2.1.0.1_

    **ESAPI 2.1.0.1:安全编程接口详解** `ESAPI`,全称为`Enterprise Security API`,是企业级安全API的一种实现,主要用于帮助开发人员在Java平台上构建更安全的应用程序。这个开源项目由OWASP(开放网络应用安全...

    esapi配置文件

    ESAPI(Enterprise Security API)是Enterprise Security API的缩写,是一个开源的安全库,主要用于Java应用程序,旨在提供一种标准的方法来处理常见的安全问题,如输入验证、输出编码、身份验证、授权、加密等。...

    OWASP ESAPI项目

    ### OWASP ESAPI项目知识点详解 #### 一、OWASP ESAPI项目概述 **OWASP ESAPI**(Enterprise Security API)是一项由开放Web应用程序安全项目(OWASP)发起的开源项目,旨在帮助软件开发者轻松地集成强大的安全性...

    Elasticsearch API

    Elasticsearch Java API是Elasticsearch提供的官方客户端之一,允许开发者通过Java代码来操作Elasticsearch,提供了一个更为便捷和安全的方式来与Elasticsearch集群交互。 入门Elasticsearch时,首先应该熟悉...

    ESAPI加使用方法文档

    **ESAPI(Enterprise Security API)** 是一个开源的安全框架,主要设计用于帮助开发人员构建更安全的Web应用程序。它提供了一套完整的接口和实现,涵盖了输入验证、输出编码、访问控制等多个安全领域,以减少常见...

    SpringBoot +esapi 实现防止xss攻击 实战代码,满满干货

    SpringBoot是一个流行的Java微服务框架,而ESAPI(Enterprise Security API)则是一个开源的安全库,旨在提供一种简便的方式来防御多种Web应用安全问题,包括XSS攻击。本实战代码将展示如何结合SpringBoot和ESAPI来...

    SpringBoot +esapi 实现防止xss攻击 实战代码

    在SpringBoot项目中集成ESAPI(Enterprise Security API)可以有效地防止XSS攻击。本文将深入探讨如何在SpringBoot应用中结合springSecurity过滤器链,利用ESAPI库实现XSS防护。 首先,让我们了解ESAPI。ESAPI是一...

    基于ESAPI的防sql注入jar包及使用示例.rar

    **基于ESAPI的防SQL注入技术** 在网络安全领域,SQL注入是一种常见的攻击手段,通过恶意构造SQL语句,攻击者可以获取、修改甚至删除数据库中的敏感数据。为了防止这种攻击,开发人员通常会采用各种防御策略,其中一...

    Spring Data Elasticsearch API(Spring Data Elasticsearch 开发文档).CHM

    Spring Data Elasticsearch API(Spring Data Elasticsearch 开发文档).CHM。 官网 Spring Data Elasticsearch API

    ESAPI 1.5专业版2014 esapi1.5 esAPI1.5 支持更新

    **ESAPI 1.5 专业版:网络安全的守护者** ESAPI,全称为"Enterprise Security API"(企业安全API),是一种开源的安全框架,旨在帮助开发者构建更安全的应用程序。这个1.5专业版2014是针对该框架的一个重要版本更新...

    spring-data-elasticsearch api 离线文档

    spring-data-elasticsearch api 离线文档, spring-data-elasticsearch2.0.2spring-data-elasticsearch api spring-data-elasticsearch api 离线文档

    使用Java调用ElasticSearch提供的相关API进行数据搜索完整实例演示

    在本文中,我们将深入探讨如何使用Java调用Elasticsearch(ES)提供的API进行数据搜索。Elasticsearch是一个流行的开源全文搜索引擎,具有分布式、实时、可扩展性等特性,广泛应用于大数据分析和日志检索等领域。...

    esapi-java-legacysource-esapi-2.1.0.1.zip

    ESAPI (Enterprise Security API) 是一个开源项目,由OWASP(Open Web Application Security Project)组织维护,旨在提供一套全面的、统一的安全编程接口,帮助Java开发者编写更安全的应用程序。这个压缩包“esapi-...

    ElasticSearch Java API 中文文档

    标签《ES Java API 中文文档》强调了文档的内容属性,它属于ElasticSearch的一个重要组成部分,即用Java语言进行数据交互和操作的应用程序接口部分。 从部分内容中可以提取出以下知识点: 1. **Transport Client**...

    esapi 2.1.0 for java

    **ESAPI 2.1.0 for Java:安全开发的重要工具** `ESAPI (Enterprise Security API)` 是一个开源的安全框架,旨在提供企业级的Web应用安全解决方案。版本2.1.0是该框架的一个重要更新,它包含了针对Java平台的接口和...

    ESAPI 1.5专业版2013 esapi1.5 esAPI1.5 支持更新

    **ESAPI 1.5 专业版 2013:Web 安全框架详解** ESAPI(Enterprise Security API)1.5 是一个强大的、开源的安全框架,专为 web 应用程序设计,旨在帮助开发者遵循最佳安全实践,降低安全漏洞的风险。这个版本发布于...

    esapi jar包

    使用esapi进行Web应用程序安全控制组件,可以帮助编程人员开发低风险应用程序。

    esapi for javascript-0.1.3

    **ESAPI for JavaScript 0.1.3:安全编程的基石** ESAPI(Enterprise Security API)是用于构建安全Web应用程序的开源库,它为开发者提供了一组标准接口,以简化安全编码并降低常见Web攻击的风险。ESAPI for ...

Global site tag (gtag.js) - Google Analytics