ElasticSearch 安装
在windows上下载,解压,进入到bin目录,双击打开elasticsearch.bat文件
双击启动窗口闪退,可以通过路径访问错误,空间不足则在config/jvm.options 配置文件中进行修改
HTTP
put 创建索引
get 获取索引
查看所有索引信息
_cat/indices?v #_cat 表示查看的意思
delete 删除索引
POST发送JSON数据
{
"name":"张三",
"age":21,
"sex":"男"
}
这里发送了2次,id是会跟着换
指定id
主键查询
全部查询
全局修改
{
"name":"张三",
"age":21,
"sex":"男",
"address":"杭州"
}
局部修改
{
"doc":{
"name":"李四"
}
}
删除数据
条件查询
条件查询-请求体查询
{
"query":{
"match":{ //match表示匹配查询
"address":"杭州"
}
}
}
全部查询-请求体查询
{
"query":{
"match_all":{ //match表示匹配查询
}
}
}
分页查询
{
"query":{
"match_all":{ //match表示匹配查询
}
},
"from":0,
"size":3,
}
只查看部分数据
{
"query":{
"match_all":{ //match表示匹配查询
}
},
"from":0,
"size":3,
"_source": ["name","age"],
}
分页+排序
{
"query":{
"match_all":{ //match表示匹配查询
}
},
"from":0,
"size":3,
"_source": ["name","age"],
"sort":{
"age":{
"order":"desc"
}
}
}
多条件查询
{
"query":{ //表示查询
"bool":{ //表示条件
"must":[ // 表示多个条件同时必须成立
{
"match":{ //匹配
"address":"南宁"
}
},
{
"match":{ //匹配
"name":"李四"
}
}
]
}
}
}
范围查询
{
"query":{ //表示查询
"bool":{ //表示条件
"should":[ // 表示有一个条件成立
{
"match":{ //匹配
"address":"南宁"
}
},
{
"match":{ //匹配
"address":"杭州"
}
}
]
}
}
}
数值范围查询
{
"query":{ //表示查询
"bool":{ //表示条件
"should":[ // 表示有一个条件成立
{
"match":{ //匹配
"address":"南宁"
}
},
{
"match":{ //匹配
"address":"杭州"
}
}
],
"filter":{ //过滤
"range":{ //范围
"age":{
"gt":30 //gt表示大于 ,lt 表示小于
}
}
}
}
}
}
全文检索
{
"query":{
"match":{
"name":"三四"
}
}
}
完全匹配
{
"query":{
"match_phrase":{
"name":"四"
}
}
}
高亮匹配
{
"highlight":{
"fields":{
"name":{}
}
}
}
聚合查询-分组查询
{
"aggs":{ //聚会操作
"age_group":{ //统计结果名称
"terms":{ //分组
"field":"age" //分组字段
}
}
},
"size":0 //表示源数据不显示,只显示统计数据
}
均值查询
"age_avg":{ //统计结果名称
"avg":{ //平均值
"field":"age" //均值字段
}
}
映射关系简单介绍
{
"properties":{
"name":{
"type":"text",// 可以被分词查询
"index":true
},
"sex":{
"type":"keyword", // 表示关键字,不能被分词
"index":true
},
"tel":{
"type":"keyword",
"index":false //表示不能被当初索引
}
}
}
JavaAPI
Maven依赖
有部分是多余的
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-elasticsearch</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
<version>2.7.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j</artifactId>
<version>1.3.8.RELEASE</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.elasticsearch.client</groupId>
<artifactId>elasticsearch-rest-client</artifactId>
<version>7.8.0</version>
</dependency>
</dependencies>
工具类配置
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
@Configuration
@Component
public class ESConfig {
@Bean
public RestHighLevelClient restHighLevelClient(){
return new RestHighLevelClient(RestClient.builder(new HttpHost("localhost",9200,"http")));
}
}
测试
import com.fasterxml.jackson.databind.ObjectMapper;
import com.zwhy.elasticsearch.entity.User;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetRequest;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.client.indices.GetIndexResponse;
import org.elasticsearch.cluster.metadata.AliasMetadata;
import org.elasticsearch.cluster.metadata.MappingMetadata;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
@RestController
public class ESController {
@Autowired
RestHighLevelClient client;
@GetMapping("/test1")
public String test1() throws IOException {
//创建索引
CreateIndexResponse createIndexResponse = client.indices()
.create(new CreateIndexRequest("user"), RequestOptions.DEFAULT);
//响应状态
boolean status = createIndexResponse.isAcknowledged();
return "索引操作:"+status;
}
@GetMapping("/test2")
public String test2() throws IOException {
//获取索引
GetIndexResponse getIndexResponse = client.indices().get(new GetIndexRequest("user"), RequestOptions.DEFAULT);
Map<String, List<AliasMetadata>> aliases = getIndexResponse.getAliases();
Map<String, MappingMetadata> mappings = getIndexResponse.getMappings();
Map<String, Settings> settings = getIndexResponse.getSettings();
return aliases.toString()+"\n"+mappings.toString()+"\n"+settings.toString();
}
@GetMapping("/test3")
public String test3() throws IOException {
//删除索引
AcknowledgedResponse delete = client.indices().delete(new DeleteIndexRequest("user"), RequestOptions.DEFAULT);
boolean status = delete.isAcknowledged();
return "删除索引结果:"+status;
}
@GetMapping("/test4")
public String test4() throws IOException {
//插入数据
User user = new User();
user.setName("张三");
user.setAge(30);
user.setSex("女");
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writeValueAsString(user);
IndexResponse index = client.index(new IndexRequest("user").id("1001")
.source(str, XContentType.JSON), RequestOptions.DEFAULT);
DocWriteResponse.Result result = index.getResult();
return result.toString();
}
@GetMapping("/test5")
public String test5() throws IOException {
//修改数据
UpdateResponse response = client.update(new UpdateRequest().index("user").id("1001")
.doc(XContentType.JSON,"name","李四"), RequestOptions.DEFAULT);
DocWriteResponse.Result result = response.getResult();
return result.toString();
}
@GetMapping("/test6")
public String test6() throws IOException {
//查询数据
GetResponse response = client.get(new GetRequest().index("user").id("1001"), RequestOptions.DEFAULT);
String str = response.getSourceAsString();
return str;
}
@GetMapping("/test7")
public String test7() throws IOException {
//删除数据
DeleteResponse response = client.delete(new DeleteRequest().index("user").id("1001"), RequestOptions.DEFAULT);
return response.toString();
}
@GetMapping("/test8")
public String test8() throws IOException {
//批量插入数据
BulkRequest request = new BulkRequest();
request.add(new IndexRequest().index("user").id("1001")
.source(XContentType.JSON, "name", "张三", "age", 38));
request.add(new IndexRequest().index("user").id("1002")
.source(XContentType.JSON, "name", "李四", "age", 28));
request.add(new IndexRequest().index("user").id("1003")
.source(XContentType.JSON, "name", "王五", "age", 18));
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
return response.toString();
}
@GetMapping("/test9")
public String test9() throws IOException {
//批量删除数据
BulkRequest request = new BulkRequest();
request.add(new DeleteRequest().index("user").id("1001"));
request.add(new DeleteRequest().index("user").id("1002"));
request.add(new DeleteRequest().index("user").id("1003"));
BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);
return response.toString();
}
@GetMapping("/dome1")
public String dome1() throws IOException {
//全量查询
SearchResponse response = client.search(new SearchRequest().indices("user")
.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery())), RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
StringBuffer sb = new StringBuffer();
for (SearchHit hit : hits) {
sb.append(hit.getSourceAsString());
}
return hits.getTotalHits()+"\t"+response.getTook()+"\n"+sb.toString();
}
@GetMapping("/dome2")
public String dome2() throws IOException {
//条件查询
SearchResponse response = client.search(new SearchRequest().indices("user")
.source(new SearchSourceBuilder().query(QueryBuilders.termQuery("age",18))), RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
StringBuffer sb = new StringBuffer();
for (SearchHit hit : hits) {
sb.append(hit.getSourceAsString());
}
return hits.getTotalHits()+"\t"+response.getTook()+"\n"+sb.toString();
}
@GetMapping("/dome3")
public String dome3() throws IOException {
//分页查询
SearchResponse response = client.search(new SearchRequest().indices("user")
.source(new SearchSourceBuilder().query(QueryBuilders.rangeQuery("age"))
.from(0).size(3).sort("age", SortOrder.DESC)), RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
StringBuffer sb = new StringBuffer();
for (SearchHit hit : hits) {
sb.append(hit.getSourceAsString());
}
return hits.getTotalHits()+"\t"+response.getTook()+"\n"+sb.toString();
}
@GetMapping("/dome4")
public String dome4() throws IOException {
//字段查询
String [] excludes = {};
String [] includes = {"name"};
SearchResponse response = client.search(new SearchRequest().indices("user")
.source(new SearchSourceBuilder().query(QueryBuilders.matchAllQuery())
.fetchSource(includes,excludes)), RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
StringBuffer sb = new StringBuffer();
for (SearchHit hit : hits) {
sb.append(hit.getSourceAsString());
}
return hits.getTotalHits()+"\t"+response.getTook()+"\n"+sb.toString();
}
@GetMapping("/dome5")
public String dome5() throws IOException {
//组合查询
SearchResponse response = client.search(new SearchRequest().indices("user")
.source(new SearchSourceBuilder()
.query(QueryBuilders.boolQuery()
.must(QueryBuilders.matchQuery("age",28))
.must(QueryBuilders.matchQuery("sex","男"))
.should(QueryBuilders.matchQuery("sex","男"))
)),
RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
StringBuffer sb = new StringBuffer();
for (SearchHit hit : hits) {
sb.append(hit.getSourceAsString());
}
return hits.getTotalHits()+"\t"+response.getTook()+"\n"+sb.toString();
}
@GetMapping("/dome6")
public String dome6() throws IOException {
//范围查询
SearchResponse response = client.search(new SearchRequest().indices("user")
.source(new SearchSourceBuilder()
.query(QueryBuilders.rangeQuery("age").gte(30).lte(50)
)
),
RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
StringBuffer sb = new StringBuffer();
for (SearchHit hit : hits) {
sb.append(hit.getSourceAsString());
}
return hits.getTotalHits()+"\t"+response.getTook()+"\n"+sb.toString();
}
@GetMapping("/dome7")
public String dome7() throws IOException {
//模糊查询
SearchResponse response = client.search(new SearchRequest().indices("user")
.source(new SearchSourceBuilder()
.query(QueryBuilders.fuzzyQuery("name","哥").fuzziness(Fuzziness.ONE)
)
),
RequestOptions.DEFAULT);
SearchHits hits = response.getHits();
StringBuffer sb = new StringBuffer();
for (SearchHit hit : hits) {
sb.append(hit.getSourceAsString());
}
return hits.getTotalHits()+"\t"+response.getTook()+"\n"+sb.toString();
}
}
…以后不定期更新