ElasticSearch使用和集成

ElasticSearch使用和集成

下载慢的小伙伴们可以到 华为云的镜像去下载
速度很快,自己找对应版本就可以
ElasticSearch: https://mirrors.huaweicloud.com/elasticsearch/?C=N&O=D
logstash: https://mirrors.huaweicloud.com/logstash/?C=N&O=D
kibana: https://mirrors.huaweicloud.com/kibana/?C=N&O=D
ik: https://github.com/medcl/elasticsearch-analysis-ik/releases;https://github.com/medcl/elasticsearch-analysis-ik/releases/tag/v7.6.1
[]
ELK三剑客,解压即用
http.cors.enabled: true
http.cors.allow-origin: "*"

bug

  1. 索引创建失败?修改jvm内存值
    https://blog.csdn.net/qq_31573519/article/details/77542506

es基本操作指令

  1. 创建文档 索引
PUT /test1/type/1
{
  "name":"lg",
  "age": 12
}
  1. 查询
    GET /test1/type1/1
  2. 修改
# 第一种方式: 版本会增加;缺点:容易会漏字段
PUT /test1/type1/1
{
  "name": "xiaoli",
  "age": 100
}
#第二种方式: 这样不会漏字段,修改指定的字段
POST /test1/_doc/1/_update
{
  "doc":{
    "name": "法外狂徒"
  }
}
  1. 删除
    通过DELETE命令实现删除,根据你的请求来判断是删除索引还是删除文档记录
DELETE test1
DELETE lg

关于文档的基本操作(重点)

  1. 基本操作
# 添加索引 对应的数据
PUT /kuangshen/user/1
{
  "name": "狂神说",
  "age": 23,
  "desc":"一顿操作稳如虎,一看战绩250",
  "tags": ["技术", "温暖", "直男"]
}
PUT /kuangshen/user/2
{
  "name": "张三",
  "age": 3,
  "desc":"法外狂徒",
  "tags": ["渣男", "搞笑", "交友"]
}
PUT /kuangshen/user/3
{
  "name": "李四",
  "age": 30,
  "desc":"不知道形容",
  "tags": ["靓女", "搞笑", "唱歌"]
}
# 获取数据
GET kuangshen/user/1

# 更新数据PUT(不推荐):如果不穿值,就会被覆盖
PUT /kuangshen/user/3
{
  "name": "李四233",
  "age": 30,
  "desc":"不知道形容",
  "tags": ["靓女", "搞笑", "唱歌"]
}
# Post _update,推荐使用这种更新方式(推荐): 灵活,想修改那个字段值就改那个。
POST kuangshen/user/1/_update
{
  "doc":{
    "name": "狂神说java312321"
  }
}

# 简单搜索
GET kuangshen/user/1
#  默认查询
GET kuangshen/user/_search?q=name:三



  1. 复杂操作 select(排序,分页,高亮,模糊,精准查询)
    分数:score: 匹配度越高,分数越高
GET kuangshen/user/_search
{
  "query": { # 查询的条件
    "match": {
      "name": "狂神"
    }
  },
  "_source": ["name", "source"] # 过滤字段
}
# hit: 

#我们之后使用java对象操作es,所有的方法和对象的这里里面的key

# 排序 通过 sort字段
GET kuangshen/user/_search
{
  "query": { # 查询的条件
    "match": {
      "name": "狂神"
    }
  },
  "sort": [ # 排序条件
    {
      "age": {
        "order": "asc"
      }
    }
  ]
    
}
# 分页 kuangshen/user/_search/{current}/{pageSize}
GET kuangshen/user/_search
{
  "query": { # 查询的条件
    "match": {
      "name": "狂神"
    }
  },
  "sort": [ # 排序条件
    {
      "age": {
        "order": "asc"
      }
    }
  ],
  "from": 0, # limit 2 个参数
  "size": 1
    
}
# 多条件查询 模糊; must多个条件 同时满足(相当于and)
GET kuangshen/user/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "name": "狂神"
          }
        },
        {
          "match": {
            "age": 23
          }
        }
      ] 
    }
  }
}
# 多条件查询 模糊; should 多个条件 满足其一即可(相当于or)
GET kuangshen/user/_search
{
  "query": {
    "bool": {
      "should": [
        {
          "match": {
            "name": "狂神"
          }
        },
        {
          "match": {
            "age": 23
          }
        }
      ] 
    }
  }
}
# 多条件查询 模糊; must_not 多个条件 满足其一即可(相当于or)
GET kuangshen/user/_search
{
  "query": {
    "bool": {
      "must_not": [
        {
          "match": {
            "age": 23
          }
        }
      ]
    }
  }
}
# 范围条件查询 模糊; range 
GET kuangshen/user/_search
{
  "query": {
    "bool": {
      "must": [
        {
          "match": {
            "name": "狂神"
          }
        }
      ],
      "filter": {
        "range": {
          "age": {
            "gte": 10,
            "lte": 20
          }
        }
      }
    }
  }
}
# 匹配多个标签查询 模糊; match 多个条件使用空格隔开
GET kuangshen/user/_search
{
  "query": {
    "match": {
      "tags": "男 搞笑"
    }
  }
}

# jin


集成springBoot

  1. POM
       <!-- es-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-elasticsearch</artifactId>
            <version>2.2.13.RELEASE</version>
        </dependency>
  1. 配置
@Configuration
public class ElasticSearchClientConfig {
    @Bean
    public RestHighLevelClient restHighLevelClient() {
        RestHighLevelClient client = new RestHighLevelClient(
                RestClient.builder(
                        new HttpHost("127.0.0.1", 9200, "http")
                )
        );
        return client;
    }
}

  1. 使用 CRUD
@RestController
@RequestMapping("/api")
public class esTest {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    //1. 创建索引
    @PostMapping("/createIndex")
    public String createIndex() throws IOException {
        //创建 一个新建索引请求
        CreateIndexRequest request = new CreateIndexRequest("coupon_index");
        //执行创建索引的请求
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSON(createIndexResponse).toString());
        //{"fragment":false,"acknowledged":true,"shardsAcknowledged":true}
        /**
         * 使用命令
         * PUT /test2
         * {
         *   "acknowledged" : true,
         *   "shards_acknowledged" : true,
         *   "index" : "test2"
         * }
         * */

        return JSON.toJSON(createIndexResponse).toString();
    }


    //2. 查询索引是否存在
    @PostMapping("/existIndex")
    public String testExistIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("coupon_index");
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSON(exists).toString());
        //true
        System.out.println(exists);
        return JSON.toJSON(exists).toString();
    }

    //3. 查询索引信息
    @PostMapping("/getIndex")
    public String testGetIndex() throws IOException {
        GetIndexRequest request = new GetIndexRequest("coupon_index");
        GetIndexResponse getIndexResponse = restHighLevelClient.indices().get(request, RequestOptions.DEFAULT);
        String s = getIndexResponse.toString();
        Object o = JSON.toJSON(getIndexResponse);
        System.out.println(o.toString());
        System.out.println(s);
        return  s;
    }

    //4. 删除索引
    @PostMapping("/deleteIndex")
    public String testDeleteIndex() throws IOException {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest("coupon_index");
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);
        System.out.println(JSON.toJSON(delete));
        //{"fragment":false,"acknowledged":true}
        return JSON.toJSON(delete).toString();
    }

    /**
     * 1. 给对应的索引, 创建文档
     * @throws IOException
     */
    @PostMapping("/createDoc")
    public String testCreateDocument() throws IOException {
        IndexRequest indexRequest = new IndexRequest("coupon_index");
        UserInfo user = new UserInfo("张飞","12123123");
        IndexRequest source = indexRequest.source(JSONObject.toJSONString(user), XContentType.JSON);
        IndexResponse index = restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);
        System.out.println(index.toString());
        //
        return index.toString();
    }

    /**
     * 2. 文档是否存在
     * @throws IOException
     */
    @PostMapping("/existDoc")
    void testExistDocument() throws IOException {
        //testapi 索引中     是否存在 1 的文档
        GetRequest getRequest = new GetRequest("coupon_index", "1");
        boolean exists = restHighLevelClient.exists(getRequest, RequestOptions.DEFAULT);
        System.out.println(exists);
    }

    /**
     * 3. 获取文档信息
     * @throws IOException
     */
    @PostMapping("/getDoc")
    void testGetDocument() throws IOException {
        GetRequest getRequest = new GetRequest("coupon_index", "gBd0W3MBYL0QvcF5Z9tv");
        GetResponse documentFields = restHighLevelClient.get(getRequest, RequestOptions.DEFAULT);
        System.out.println(documentFields.getSource());
    }

    /**
     * 4. 更新文档信息
     * @throws IOException
     */
    @PostMapping("/updateDoc")
    void testUpdatDocument() throws IOException {
        UpdateRequest updateRequest = new UpdateRequest("coupon_index", "jxeBW3MBYL0QvcF5idvD");
        UserInfo user = new UserInfo("张飞","坦克");
        updateRequest.doc(JSONObject.toJSONString(user),XContentType.JSON);
        UpdateResponse update = restHighLevelClient.update(updateRequest, RequestOptions.DEFAULT);
        System.out.println(update.status());
    }

    /**
     * 5. 删除文档信息
     * @throws IOException
     */
    @PostMapping("/deleteDoc")
    void testDeleteDocument() throws IOException {
        DeleteRequest deleteRequest = new DeleteRequest("coupon_index", "jxeBW3MBYL0QvcF5idvD");
        DeleteResponse delete = restHighLevelClient.delete(deleteRequest, RequestOptions.DEFAULT);
        System.out.println(delete.status());
    }

    /**
     * 6. 查询文档 条件
     */
    @PostMapping("/getDocByContion")
    void testSearchDocument() throws IOException {
        SearchRequest searchRequest = new SearchRequest("coupon_index");
        //匹配字段
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("username", "李白");
        //构建查询器
        searchRequest.source(new SearchSourceBuilder().query(matchQueryBuilder));
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);
        System.out.println(searchResponse.getHits().getTotalHits());
    }

}

实战

爬虫

前后端分离

搜索高亮

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,284评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,115评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,614评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,671评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,699评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,562评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,309评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,223评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,668评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,859评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,981评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,705评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,310评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,904评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,023评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,146评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,933评论 2 355

推荐阅读更多精彩内容