ElasticSearch实战(七) API

  • 创建索引
Request request = new Request("PUT", "/something");
request.setJsonEntity(settingsAndMapping);
restClient.performRequest(request);

settingsAndMapping

{
	"settings": {
		"index": {
			"search": {
				"slowlog": {
					"threshold": {
						"query": {
							"info": "100ms"
						}
					}
				}
			},
			"number_of_shards": "5",
			"number_of_replicas": "1"
		}
	},
	"mappings": {
		"sometype": {
			"properties": {
				"author": {
					"type": "text",
					"fields": {
						"keyword": {
							"type": "keyword",
							"ignore_above": 256
						}
					}
				},
				"date": {
					"type": "date"
				},
				"id": {
					"type": "long"
				},
				"likes": {
					"type": "long"
				},
				"text": {
					"type": "text",
					"analyzer": "ik_max_word",
					"search_analyzer": "ik_smart"
				}
			}
		}
	}
}
  • 删除索引
Request request = new Request("DELETE", "/something");
restClient.performRequest(request);
  • 索引一个文档
Request request = new Request("POST", "/something/sometype/");
request.setJsonEntity("{\"author\":\"Mary Jones\",\"text\":\"Jane is an expert in her field\",\"tags\":\"expert\",\"likes\":80,\"date\":\"2019-06-21\"}");
restClient.performRequest(request);
  • 指定ID索引文档
Request request = new Request("PUT", "/something/sometype/1/_create");
request.setJsonEntity("{\"author\":\"Jane Smith\",\"text\":\"I am starting to get the hang of this...\",\"likes\":0,\"date\":\"2019-06-20\"}");
restClient.performRequest(request);
  • 获取文档
Request request = new Request("GET", "/something/sometype/1");
Response response = restClient.performRequest(request);
  • 检查文档是否存在
Request request = new Request("HEAD", "/something/sometype/2");
Response response = restClient.performRequest(request);
if(response.getStatusLine().getStatusCode() == 404) {
   //不存在
}
  • 更新文档
Request request = new Request("PUT", "/something/sometype/1/_create");
request.setJsonEntity("{\"author\":\"Jane Smith\",\"text\":\"I am starting to get the hang of this...\",\"likes\":1,\"date\":\"2019-06-20\"}");
restClient.performRequest(request);
  • 删除文档
Request request = new Request("DELETE", "/something/sometype/1");
restClient.performRequest(request);
  • 局部更新
Request request = new Request("POST", "/something/sometype/1/_update");
request.setJsonEntity("{\"doc\":{\"likes\":1}}");
restClient.performRequest(request);
  • 空搜索
Request request = new Request("GET", "/something/sometype/_search?from=0&size=10");
Response response = restClient.performRequest(request);
  • 搜索
Request request = new Request("GET", "/something/sometype/_search?q=" + java.net.URLEncoder.encode("author:Jones", "UTF-8"));
Response response = restClient.performRequest(request);

查询字符串的一些示例

q=Smith
q=author:Smith
q=+author:Smith +text:to
q=+author:Smith -text:like
q=+author:(Mary Fir John)
q=+author:(Mary Fir John) +date:>2019-06-18
q=date:2019
q=date:2019-06-20
q=likes:>=40

 

你可能感兴趣的:(Elasticsearch)