ElasticSearch汇总请查看:ElasticSearch教程——汇总篇
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
Settings settings = Settings.builder()
.put("cluster.name", "elasticsearch").build();
TransportClient client= = new PreBuiltTransportClient(settings). addTransportAddress(new TransportAddress(InetAddress.getByName("XXX.XXX.XX.XX"), 9300));
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()) {
System.out.println(hit.getId());
if (hit.getFields().containsKey("title")) {
System.out.println("field.title: "+ hit.getFields().get("title").getValue());
}
System.out.println("source.title: " + hit.getSource().get("title"));
}
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
searchSourceBuilder.query(QueryBuilders.termQuery("sid_s", text));
Search search = new Search.Builder(searchSourceBuilder.toString()).addIndex("webpage").build();
try {
SearchResult result = client.execute(search);
}catch(Exception e){
e.printStackTrace();
}
queryBuilder = QueryBuilders.matchAllQuery().boost(11f).normsField("title");
queryBuilder = QueryBuilders
.matchQuery("message", "a quick brown fox")
.operator(Operator.AND)
.zeroTermsQuery(ZeroTermsQuery.ALL);
queryBuilder = QueryBuilders.geoShapeQuery("location",
ShapeBuilder.newRectangle()
.topLeft(13, 53)
.bottomRight(14, 52)
.build());
SearchResponse response = client.prepareSearch("library")
.setQuery(QueryBuilders.matchAllQuery())
.setFrom(10) //跳过前10个文档
.setSize(20) //获取20个文档
.execute().actionGet();
response.getHits().totalHits()//可以统计当前匹配到的结果数
searchSourceBuilder.fetchSource(null, "content").sort("_score");
searchSourceBuilder.sort("date", SortOrder.DESC);
SortBuilders.scriptSort(script, type) //使用脚本来实现排序
SortBuilders.geoDistanceSort(fieldName) //根据空间距离来进行排序
QueryBuilder filterBuilder = QueryBuilders
.filteredQuery(
QueryBuilders.existsQuery("title").queryName("exist"),
QueryBuilders.termQuery("title", "elastic")
);
SearchResponse response = client.prepareSearch("library")
.setPostFilter(filterBuilder)
.execute().actionGet();
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()) {
HighlightField hField = hit.getHighlightFields().get("title");
for (Text t : hField.fragments()) {
System.out.println(t.string());
}
}
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()) {
System.out.println("Check for: " + entry.getText() + ". Options:");
for( Option option : entry.getOptions()) {
System.out.println("\t" + option.getText());
}
}
CountResponse response = client.prepareCount("library")
.setQuery(QueryBuilders.termQuery("title", "elastic"))
.execute().actionGet();
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();
MultiGetResponse response = client.prepareMultiGet()
.add("library", "book", "1", "2")
.execute().actionGet();
MultiSearchResponse response = client.prepareMultiSearch()
.add(client.prepareSearch("library", "book").request())
.add(client.prepareSearch("news").
.setPostFilter(QueryBuilders.termQuery("tags", "important")))
.execute().actionGet();
IndexResponse response = client
.prepareIndex("library", "book", "2")
.setSource("{ \"title\": \"Mastering ElasticSearch\"}")
.execute().actionGet();
Map 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();
ClusterHealthResponse response = client.admin().cluster()
.prepareHealth("library")
.execute().actionGet();
ClusterStateResponse response = client.admin().cluster()
.prepareState()
.execute().actionGet();
Map map = Maps.newHashMap();
map.put("indices.ttl.interval", "10m");
ClusterUpdateSettingsResponse response = client.admin().cluster()
.prepareUpdateSettings()
.setTransientSettings(map)
.execute().actionGet();
ClusterRerouteResponse response = client.admin().cluster()
.prepareReroute()
.setDryRun(true) //阻止分配命令的运行,仅允许下面两个给定命令(move命令 + cacel命令)的执行
.add(new MoveAllocationCommand(new ShardId("library", 3), "G3czOt4HQbKZT1RhpPCULw","PvHtEMuRSJ6rLJ27AW3U6w"),
new CancelAllocationCommand(new ShardId("library", 2), "G3czOt4HQbKZT1RhpPCULw",true))
.execute().actionGet();
NodesInfoResponse response = client.admin().cluster()
.prepareNodesInfo()
.setHttp(true) //响应中包括http信息
.setPlugins(true) //响应中包括插件信息
.execute().actionGet();
NodesStatsResponse response = client.admin().cluster()
.prepareNodesStats()
.all()
.execute().actionGet();
NodesHotThreadsResponse response = client.admin().cluster()
.prepareNodesHotThreads()
.execute().actionGet();
//输出哪些节点将处理路由值为12的查询
ClusterSearchShardsResponse response = client.admin().cluster()
.prepareSearchShards()
.setIndices("library")
.setRouting("12")
.execute().actionGet();
IndicesExistsResponse response = client.admin().indices()
.prepareExists("books", "library")
.execute().actionGet();
TypesExistsResponse response = client.admin().indices()
.prepareTypesExists("library")
.setTypes("book")
.execute().actionGet();
IndicesStatsResponse response = client.admin().indices()
.prepareStats("library")
.all()
.execute().actionGet();
IndicesStatsResponse response = client.admin().indices()
.prepareStatus("library")
.setRecovery(true)
.execute().actionGet();
IndicesSegmentResponse response = client.admin().indices()
.prepareSegments("library")
.execute().actionGet();
Creating an index API 创建索引
CreateIndexResponse response = client.admin().indices()
.prepareCreate("news")
.setSettings(Settings.settingsBuilder()
.put("number_of_shards", 1)) //分片数为1
.addMapping("news", XContentFactory.jsonBuilder()
.startObject()
.startObject("news")
.startObject("properties")
.startObject("title")
.field("analyzer", "whitespace")
.field("type", "string")
.endObject()
.endObject()
.endObject()
.endObject())
.execute().actionGet();
DeleteIndexResponse response = client.admin().indices()
.prepareDelete("news")
.execute().actionGet();
CloseIndexResponse response = client.admin().indices()
.prepareClose("library")
.execute().actionGet();
OpenIndexResponse response = client.admin().indices()
.prepareOpen("library")
.execute().actionGet();
RefreshResponse response = client.admin().indices()
.prepareRefresh("library")
.execute().actionGet();
FlushResponse response = client.admin().indices()
.prepareFlush("library")
.setFource(false)
.execute().actionGet();
OptimizeResponse response = client.admin().indices()
.prepareOptimize("library")
.setMaxNumSegments(2) //最大索引段为2
.setFlush(true)
.setOnlyExpungeDeletes(false)
.execute().actionGet();
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();
IndicesAliasesResponse response = client.admin().indices()
.prepareAliases()
.addAlias("news", "n")
.addAlias("library", "elastic_books",
QueryBuilders.termQuery("title", "elasticsearch"))
.removeAlias("news", "current_news") //移除news索引的别名current_news
.execute().actionGet();
GetAliasesResponse response = client.admin().indices()
.prepareGetAliases("elastic_books", "n")
.execute().actionGet();
AliasesExistResponse response = client.admin().indices()
.prepareAliasesExist("elastic*", "unknown") //以elastic开头 || 为unknown 的别名
.execute().actionGet();
ClearIndicesCacheResponse response = client.admin().indices()
.prepareClearCache("library")
.setFieldDataCache(true)
.setFields("title") //清空标题缓存
.setQueryCache(true) //清空过滤器缓存
.execute().actionGet();
UpdateSettingsResponse response = client.admin().indices()
.prepareUpdateSettings("library")
.setSettings(Settings.builder()
.put("index.number_of_replicas", 2)) //将副本数更新为2
.execute().actionGet();
//主要是用来检查在library索引中使用whitespace分词器 + nGram过滤器处理“ElasticSerch Servers”短语的分析处理
AnalyzeResponse response = client.admin().indices()
.prepareAnalyze("library", "ElasticSearch Servers")
.setTokenizer("whitespace")
.setTokenFilters("nGram")
.execute().actionGet();
PutIndexTemplateResponse response = client.admin().indices()
.preparePutTemplate("my_template") //my_template模板名称
.setTemplate("product*") //可以被任何以product开头的索引使用
.setSettings(Settings.builder()
.put("index.number_of_replicas", 2) //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();
DeleteIndexTemplateResponse response = client.admin().indices()
.prepareDeleteTemplate("my_*") //删除以my_开头的模板
.execute().actionGet();