Elasticsearch常用的java操作

https://blog.csdn.net/changong28/article/details/38445805

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();


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;
 
设置设置= ImmutableSettings.settingsBuilder()。put(“cluster.name”,“escluster2”)。build();
TransportClient客户端=新的TransportClient(设置);
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。


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。


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>系统。 out.println(“field.title:”+ hit.getFields()。get(“title”)。getValue());
<span style =“
</ span> System.out.println(“source.title:”+ hit.getSource()。get(“title”));
}






3.3.2构建查询
代码:
进口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使用匹配所有文件查询
代码:
queryBuilder = QueryBuilders。



3.3.4匹配查询
代码:
queryBuilder = QueryBuilders
.matchQuery(“message”,“一个快速的棕色狐狸”)
.operator(Operator.AND)
.zeroTermsQuery(ZeroTermsQuery.ALL);


3.3.5使用地理形状查询
代码:
QueryBuilder的= QueryBuilders.geoShapeQuery( “位置”,
ShapeBuilder.newRectangle()
.topLeft(13,53)
.bottomRight(14,52)
.build());
3.3.6分页查询
代码:
SearchResponse response = client.prepareSearch(“library”)。
setQuery(QueryBuilders.matchAllQuery())。
setFrom(10)
.setSize(20)
.execute()。actionGet();


3.3.7排序
代码:
SearchResponse response = client.prepareSearch(“
.setQuery(QueryBuilders.matchAllQuery())。
addSort(SortBuilders.fieldSort(“title”))。
addSort(“_ score”,SortOrder.DESC)
.execute()。actionGet()


3.3.8过滤
代码:
FilterBuilder filterBuilder = FilterBuilders
.andFilter(
FilterBuilders.existsFilter(“title”)。filterName(“exists”),
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”,“
SearchResponse response = client.prepareSearch(“library”)。
addFacet(facetBuilder)
.execute()。actionGet();




3.3.10突出显示
代码:
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:
</跨度>的System.out.println(t.string());
<span style =“white-space:pre”> </ span>}
}


3.3.11建议
代码:
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( “检查:”+ entry.getText()+“。选项:”);
<span style =“
<span style =“white-space:pre”> </ span> System.out.println(“\ t”+ option.getText());
<span style =“white-space:pre”> </ span>}
}


3.3.12计数
代码:
CountResponse response = client.prepareCount(“library”)。
setQuery(QueryBuilders.termQuery(“title”,“elastic”) )
.execute()。actionGet();
3.3.13滚动
代码:
SearchResponse responseSearch = client.prepareSearch(“library”)。
setScroll(“1m”)。
setSearchType(SearchType.SCAN)
.execute()。actionGet();
String scrollId = responseSearch.getScrollId();
SearchResponse response = client.prepareSearchScroll(scrollId).execute()。actionGet();


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按查询删除
代码:
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多搜索
代码:
MultiSearchResponse response = client.prepareMultiSearch()
.add(client.prepareSearch(“library”,“book”)。request())。
add(client.prepareSearch(“news”)。
setFilter(FilterBuilders.termFilter(“tags”,“important”)))
。执行()actionGet();




3.3.17构建JSON查询和文档
代码:
IndexResponse response = client
.prepareIndex(“library”,“book”,“2”)。
setSource(“{\”title \“:\”Mastering ElasticSearch \“}”)
。执行()actionGet();
 
Map <String,Object> m = Maps.newHashMap();
m.put(“1”,“简介”);
m.put(“2”,“基础”);
m.put(“3”,“其余”);
XContentBuilder json = XContentFactory。



.nu​​llField(“published”)。field(“chapter
”)。map(m)
.field(“title”,“Mastering ElasticSearch”)。
array(“tags”,“search”,“ElasticSearch”,“nosql”).field
(“values”)。
startArray()。value(
1)
.value(10)
.endArray()。
endObject();


3.4管理API
3.4.1集群管理API
3.4.1.1集群和索引运行状况API
代码:
ClusterHealthResponse response = client.admin()。cluster().
prepareHealth(“library”)。
execute()。actionGet();


3.4.1.2集群状态API
代码:
ClusterStateResponse response = client.admin()。cluster()




3.4.1.3更新设置API
代码:
Map <String,Object> map = Maps.newHashMap();
map.put(“indices.ttl.interval”,“10m”);
ClusterUpdateSettingsResponse响应= client.admin()簇()。
.prepareUpdateSettings()
.setTransientSettings(地图)
.execute()actionGet();


3.4.1.4的重路由API
代码:
。ClusterRerouteResponse响应= client.admin()簇()
.prepareReroute()
.setDryRun(真)
。新增(新MoveAllocationCommand(新ShardId( “文库”,3), “G3czOt4HQbKZT1RhpPCULw”,PvHtEMuRSJ6rLJ27AW3U6w “),
     new CancelAllocationCommand(new ShardId(”library“,2),”G3czOt4HQbKZZT1RhpPCULw“,rue))。
execute()。actionGet();


3.4.1。
代码:
。NodesInfoResponse响应= client.admin()簇()
.prepareNodesInfo()
.setNetwork(真)
.setPlugin(真)
。.execute()actionGet();


3.4.1.6节点统计API
代码:
。NodesStatsResponse响应= client.admin()簇()
.prepareNodesStats()
所有()
。.execute()actionGet();


3.4.1.7节点热线程API
代码:
NodesHotThreadsResponse响应= client.admin()簇()。
.prepareNodesHotThreads()
.execute()actionGet();


3.4.1.8节点停机API
代码:
NodesShutdownResponse响应= client.admin()簇()。
.prepareNodesShutdown()
.execute()actionGet();
3.4.1.9搜索碎片API
代码:
ClusterSearchShardsResponse响应= client.admin()簇()。
.prepareSearchShards()
.setIndices( “文库”)
.setRouting( “12”)
.execute()actionGet();
3.4.2 Indices管理API
3.4.2.1索引存在API
代码:
IndicesExistsResponse response = client.admin()。indices().
prepareExists(“books”,“library”)。
execute()。actionGet();




3.4.2.2类型存在API
代码:
TypesExistsResponse response = client.admin()。indicess().
prepareTypesExists(“library”)。
setTypes(“book”)。
execute()。actionGet();




3.4.2.3索引统计API
代码:
。IndicesStatsResponse响应= client.admin()索引()
.prepareStats( “库”)
所有()
.execute()actionGet();


3.4.2.4索引状态
代码:
IndicesStatusResponse response = client.admin()。indicess().
prepareStatus(“library”)。
setRecovery(true)
.setSnapshot(true)
.execute()。actionGet();




3.4.2.5分段信息API
代码:
IndicesSegmentResponse response = client.admin()。indicess().
prepareSegments(“library”)。
execute()。actionGet();




3.4.2.6创建索引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
( “分析器”, “空白”)
的点域( “类型”, “字符串”)
.endObject()
.endObject()
.endObject()
.endObject())
.execute()actionGet();




3.4.2.7删除索引
代码:
DeleteIndexResponse response = client.admin()。indicess().
prepareDelete(“news”)。
execute()。actionGet();




3.4.2.8关闭索引
代码:
CloseIndexResponse response = client.admin()。indices()






3.4.2.9打开索引
代码:
OpenIndexResponse response = client.admin()。indicess().
prepareOpen(“library”)。
execute()。actionGet();




3.4.2.10 Refresh API
代码:
RefreshResponse response = client.admin()。indicess().
prepareRefresh(“library”)。
execute()。actionGet();




3.4.2.11 Flush API
代码:
FlushResponse response = client.admin()。indicess().
prepareFlush(“library”)。
setFull(false)
.execute()。actionGet();




3.4.2.12 Optimize API
代码:
OptimizeResponse response = client.admin()。indicess().
prepareOptimize(“library”)。
setMaxNumSegments(2)
.setFlush(true)

。.execute()actionGet();


3.4.2.13 put映射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删除映射API
代码:
DeleteMappingResponse response = client.admin()。indices().
prepareDeleteMapping(“

。.execute()actionGet();




3.4.2.15网关快照API
代码:
GatewaySnapshotResponse response = client.admin()。indicess().
prepareGatewaySnapshot(“news”)。
execute()。actionGet();


3.4.2.16别名API
代码:
。IndicesAliasesResponse响应= client.admin()索引()
.prepareAliases()
.addAlias( “新闻”, “N”)
.addAlias( “库”, “elastic_books”, 
FilterBuilders.termFilter( “title”,“
elasticsearch ”))。removeAlias(“news”,“current_news”)。
execute()。actionGet();




3.4.2.17 get aliases API
代码:
IndicesGetAliasesResponse response = client.admin()。indices()






3.4.2.18别名存在API
代码:
AliasesExistResponse response = client.admin()。indices().
prepareAliasesExist(“elastic *”,“unknown”)。
execute()。actionGet();




3.4.2.19 clear cache API
代码:
ClearIndicesCacheResponse response = client.admin()。indices().
prepareClearCache(“library”)。
setFieldDataCache(true)
.setFields(“title”)。
setFilterCache(true)
.setIdCache(true)
。.execute()actionGet();




3.4.2.20更新设置API
代码:
UpdateSettingsResponse response = client.admin()。indices().
prepareUpdateSettings(“library”)。
setSettings(ImmutableSettings.builder()。
output(“index。
。.execute()actionGet();




3.4.2.21 analyze API
代码:
AnalyzeResponse response = client.admin()。indices().
prepareAnalyze(“library”,“ElasticSearch Servers”)。
setTokenizer(“whitespace”)。
setTokenFilters(“nGram”)。
execute() .actionGet();




3.4.2.22 put模板API
代码:
PutIndexTemplateResponse response = client.admin()。indicess().
preparePutTemplate(“my_template”)。
setTemplate(“product *”)。
setSettings(ImmutableSettings.builder()。
output(“index。 number_of_replicas“,2)
.put(”index.number_of_shards“,1))。
addMapping(”item“,XContentFactory.jsonBuilder()。
startObject()


.startObject( “标题”)
的点域( “类型”, “字符串”)
.endObject()
.endObject()
.endObject()
.endObject())
.execute()actionGet();


3.4.2.23删除模板API
代码:
DeleteIndexTemplateResponse response = client.admin()。indicess().
prepareDeleteTemplate(“my_ *”)。
execute()。actionGet();




3.4.2.24验证查询API
代码:
ValidateQueryResponse response = client.admin()。indicess().
prepareValidateQuery(“library”)。
setExplain(true)
.setQuery(XContentFactory.jsonBuilder()。
startObject()。field
(“name” “)。value(”弹性搜索“)
。endObject()。bytes())。
execute()。


3.4.2.25 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该删除温暖API
代码:
DeleteWarmerResponse响应= client.admin()索引()。
.prepareDeleteWarmer()
.setName( “library_ *”)
.execute()actionGet();
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值