前段时间我大学的辅导员过生日，实在不知道送她什么了，然后看到在网上看到最近很火的微信推送，就想着送这个给她把，他最喜欢明星就周杰伦、李健、玄彬等，每天都会随机推送一张图片给她，还有每天随机一首个的名称，最终效果是这样的：点击详情就可以看到那几个明星中的随机一张图片。下面分享的则是去掉了这些功能的：PHP代码为：index.php文件为：<?php /* * @Descripttion: 微信推送 * @version: 1.0 * @Author: 默然 * @Date: 2022-10-04 01:35:27 * @LastEditors: 默然 * @LastEditTime: 2022-10-05 08:00:33 */ include_once "function.php"; /** 微信公众号信息配置 */ $WXconfig = array( 'app_id' => '1', //公众号appId 'app_secret' => '1', //公众号appSecret 'touser' => '1', //公众号appSecret 'template_id' => '1', //公众号appSecret ); //获取access_token $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $WXconfig['app_id'] . "&secret=" . $WXconfig['app_secret']; $returnJson = json_decode(curl_http($url), true); $token = $returnJson["access_token"]; if (!$token) { $return = array( "code" => $returnJson['errcode'], "msg" => "获取access_token失败，请检查app_id和app_secret是否正确", ); exit(json_encode($returnJson)); } //获取天气预报的所有信息 $weatherinfo = getweather(0); //发送消息 $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" . $token; $posts = array( "touser" => $WXconfig['touser'], "template_id" => $WXconfig['template_id'], "url" => "", "topcolor" => getcolor(), "data" => array( "date" => array( "value" => "今天是" . date("Y年m月d日", time()) . $weatherinfo["week"], "color" => getcolor(), ), "region" => array( "value" => "昆明市", "color" => getcolor(), ), "weather" => array( "value" => $weatherinfo["weather"], "color" => getcolor(), ), "high" => array( "value" => $weatherinfo["high"], "color" => getcolor(), ), "low" => array( "value" => $weatherinfo["low"], "color" => getcolor(), ), "fortoday" => array( "value" => $weatherinfo["notice"], "color" => getcolor(), ), "vhanzh" => array( "value" => getian()[0]["mingrenmingyan"], "color" => getcolor(), ), "zhufu" => array( "value" => $zhufu, "color" => getcolor(), ), ), ); $rs = curl_http($url, 1, $posts); echo $rs; function.php文件为：<?php /* * @Descripttion: 公共方法合集 * @version: 1.0 * @Author: 默然 * @Date: 2022-10-04 01:35:27 * @LastEditors: 默然 * @LastEditTime: 2022-10-04 21:04:12 */ /** * curl 函数 * @param string $url 请求的地址 * @param string $type 1 post传输 0为get * @param array $data 要传输的数据 */ function curl_http($url, $type = 0, $data = []) { // 创建一个新cURL资源 $ch = curl_init(); // 设置URL和相应的选项 curl_setopt($ch, CURLOPT_URL, $url); //$url设置需要请求的url curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_MAXREDIRS, 10); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); //是否设置为post请求和请求参数 if ($type == 1) { curl_setopt($ch, CURLOPT_POST, 1); // 发送一个常规的Post请求 curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data)); // Post提交的数据包 } // 抓取URL并把它传递给浏览器 $output = curl_exec($ch); // 关闭cURL资源，并且释放系统资源 curl_close($ch); return $output; } //获取随机颜色 function getcolor() { $colors = array(); for ($i = 0; $i < 6; $i++) { $colors[] = dechex(rand(0, 15)); } return "#" . implode('', $colors); } //获取天气预报 function getweather($day) { //这里city后面得数字具体换成自己当地的 $url = "http://t.weather.sojson.com/api/weather/city/101290101"; $returnJson = json_decode(curl_http($url), true); $rs = $returnJson["data"]["forecast"][$day]; //重新组装数据 $data["week"] = $rs["week"]; $data["weather"] = $rs["type"]; $data["high"] = substr(strstr($rs["high"], " "), 1); $data["low"] = substr(strstr($rs["low"], " "), 1); $data["notice"] = $rs["notice"]; return $data; } //获取一言 function getian() { $url = "https://v.api.aa1.cn/api/api-wenan-mingrenmingyan/index.php?aa1=json"; $returnJson = json_decode(curl_http($url), true); return $returnJson; } 模板文件为：{{date.DATA}} 地区：{{region.DATA}} 天气：{{weather.DATA}} 最高气温：{{high.DATA}} 最低气温：{{low.DATA}} 今日建议：{{fortoday.DATA}} {{vhanzh.DATA}} {{zhufu.DATA}}
前段时间做云后台管理系统的时候，群友一直说需要接口加密，所以就看了一下相关方面的代码，话不多说，直接上代码：PHP加密解密方法： /** * 加密字符串 * * @param [type] $input 加密字符串 * @param [type] $securityKey 密钥 */ public static function WeDoctorEncrypt($input, $securityKey) { //进行Aes加密 $data = openssl_encrypt($input, 'AES-128-ECB', $securityKey); return urlencode($data); } /** * 解密字符串 * * @param [type] $input 解密字符串 * @param [type] $securityKey 密钥 */ public static function WeDecrypt($input, $securityKey) { $input = urldecode($input); $input = openssl_decrypt($input, 'AES-128-ECB', $securityKey); if (!$input) { return self::returnjson(400, "服务器错误"); } return $input; } /** * 密钥生成方法 * * @return string */ function getRandChar() { $str = null; $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz"; $max = strlen($strPol) - 1; for ($i = 0; $i < 16; $i++) { $str .= $strPol[rand(0, $max)]; } return $str; }接下来我们写个方法测试一下： public function test() { //需加密的字符串 $str = "www.moranblog.cn"; echo "原始字符串：".$str; echo " "; //进行加密 $en_str = Common::WeDoctorEncrypt($str,"LwbPsFsjYyWorEdD"); echo "加密后：". $en_str; echo " "; //进行解密 echo "解密后：". Common::WeDecrypt($en_str,"LwbPsFsjYyWorEdD"); }最终结果：接下来说一下java 的加解密方法：import java.util.Base64; import javax.crypto.Cipher; import javax.crypto.spec.SecretKeySpec; public class AES { /** * 加密算法 * * @param sSrc 加密字符串 * @param sKey 密钥 * @return * @throws Exception */ public static String Encrypt(String sSrc, String sKey) throws Exception { if (sKey == null) { System.out.print("Key为空null"); return null; } // 判断Key是否为16位 if (sKey.length() != 16) { System.out.print("Key长度不是16位"); return null; } byte[] raw = sKey.getBytes("utf-8"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // "算法/模式/补码方式" cipher.init(Cipher.ENCRYPT_MODE, skeySpec); byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8")); String result = Base64.getEncoder().encodeToString(encrypted); return java.net.URLEncoder.encode(result, "UTF-8"); // 此处使用BASE64做转码功能，同时能起到2次加密的作用。 } /** * * @param sSrc 解密字符串 * @param sKey 解密算法 * @return * @throws Exception */ public static String Decrypt(String sSrc, String sKey) throws Exception { try { // 判断Key是否正确 if (sKey == null) { System.out.print("Key为空null"); return null; } // 判断Key是否为16位 if (sKey.length() != 16) { System.out.print("Key长度不是16位"); return null; } byte[] raw = sKey.getBytes("utf-8"); SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skeySpec); try { sSrc = java.net.URLDecoder.decode(sSrc, "UTF-8"); byte[] encrypted1 = Base64.getDecoder().decode(sSrc); // 先用base64解密 byte[] original = cipher.doFinal(encrypted1); String originalString = new String(original, "utf-8"); return originalString; } catch (Exception e) { System.out.println(e.toString()); return null; } } catch (Exception ex) { System.out.println(ex.toString()); return null; } } public static void main(String[] args) throws Exception { /* * 此处使用AES-128-ECB加密模式，key需要为16位。 */ String cKey = "LwbPsFsjYyWorEdD"; // 需要加密的字串 String cSrc = "www.moranblog.cn"; System.out.println(cSrc); // 加密 String enString = AES.Encrypt(cSrc, cKey); System.out.println("加密后的字串是：" + enString); // 解密 String DeString = AES.Decrypt(enString, cKey); System.out.println("解密后的字串是：" + DeString); } } 运行结果：
安装好后在bin目录下新建mysql.conf，配置一下内容：input { jdbc { # mysql数据库连接 jdbc_connection_string => "jdbc:mysql://127.0.0.1:3306/esdemo?useUnicode=true&characterEncoding=utf8&serverTimezone=Asia/Shanghai" # mysqly用户名和密码 jdbc_user => "root" jdbc_password => "123456" # 驱动配置 jdbc_driver_library => "D:\elasticsearch\logstash-8.2.0\mysql-connector-java-5.1.7-bin.jar" # 驱动类名 jdbc_driver_class => "com.mysql.jdbc.Driver" # 数据库重连尝试次数 connection_retry_attempts => "3" # 判断数据库连接是否可用，默认false不开启 jdbc_validate_connection => "true" # 数据库连接可用校验超时时间，默认3600S jdbc_validation_timeout => "3600" # 开启分页查询（默认false不开启）； jdbc_paging_enabled => "true" # 单次分页查询条数（默认100000,若字段较多且更新频率较高，建议调低此值）； jdbc_page_size => "50000" # statement为查询数据sql，如果sql较复杂，建议配通过statement_filepath配置sql文件的存放路径； # sql_last_value为内置的变量，存放上次查询结果中最后一条数据tracking_column的值，此处即为ModifyTime； # 执行指定的sql文件 #statement_filepath => "D:\service\logstash-7.7.0\mysql\sql\fa_search.sql" #执行的sql语句 statement => "SELECT * FROM syshl1 where id > :sql_last_value order by id asc" # 是否将字段名转换为小写，默认true（如果有数据序列化、反序列化需求，建议改为false）； lowercase_column_names => false # Value can be any of: fatal,error,warn,info,debug，默认info； sql_log_level => warn # 是否记录上次执行结果，true表示会将上次执行结果的tracking_column字段的值保存到last_run_metadata_path指定的文件中； record_last_run => true # 需要记录查询结果某字段的值时，此字段为true，否则默认tracking_column为timestamp的值； use_column_value => true # 需要记录的字段，用于增量同步，需是数据库字段 tracking_column => "id" #追踪字段的类型，目前只有数字(numeric)和时间类型(timestamp)，默认是数字类型() tracking_column_type => "numeric" # record_last_run上次数据存放位置； last_run_metadata_path => "D:\elasticsearch\logstash-8.2.0\last_id.txt" # 是否清除last_run_metadata_path的记录，需要增量同步时此字段必须为false； clean_run => false # 设置监听 各字段含义 分 时 天 月 年 ，默认全部为*代表含义：每分钟都更新 schedule => "* * * * *" # 索引类型 #type => "blog" } } filter { json { source => "message" remove_field => ["message"] } } output { elasticsearch { #es服务器 hosts => ["localhost:9200"] #ES索引名称 index => "syshl" #自增ID document_id => "%{id}" } stdout { codec => json_lines } }然后通过 logstash -f bin/mysql.conf 去启动；成功后开始同步数据
连接Elasticsearch这里采用集群的方式，所以需要启动多个Elasticsearch实例。$parms = [ "localhost:1001", "localhost:1002", "localhost:1003", ]; //连接elasticsearch $this->client = \Elasticsearch\ClientBuilder::create()->setHosts($parms)->build;创建索引$params = [ 'index' => 'user', 'body' => [ 'settings' => [ 'number_of_shards' => 3, 'number_of_replicas' => 2 ] ] ] echo json_encode($this->client->indices()->create($params));返回结果：{ "acknowledged": true, //索引是否创建成功 "shards_acknowledged": true, //分片是否创建成功 "index": "user" //索引名称 }删除索引$params = [ 'index' => 'user', ]; echo json_encode($this->client->delete($params));返回结果：{ "acknowledged": true //确认是否删除成功 }获取文档$params = [ 'index' => 'user', //索引名称 'type' => 'user', //类型名称 'id' => '1', ]; echo json_encode($this->client->get($params));返回结果：{ "_index": "user", //索引名称 "_type": "user", //类型名称 "_id": "1", //文档id "_version": 2, //版本号 "_seq_no": 30, //序列号 "_primary_term": 1, //主键 "found": true, //是否找到 "_source": { //文档内容 "uid": 1, "username": "test", "signature": "test", "phone": "13276535811", "money": "100", "address": "天津 天津市 东丽区", "create_time": 1652340350 } }修改文档$params = [ 'index' => 'user', //索引名称 'type' => 'user', //类型名称 'id' => '1', //文档id 'body' => [ //文档内容 'uid' => 1, 'username' => 'test', 'signature' => 'test', 'phone' => '13276535811', 'money' => '100', 'address' => '天津 天津市 东丽区', 'create_time' => time(), ], ]; echo json_encode($this->client->index($params));返回结果：{ "_index": "user", //索引名称 "_type": "user", //类型名称 "_id": "1", //文档id "_version": 2, //版本号 "result": "updated", //操作结果 "_shards": { "total": 3, //分片总数 "successful": 3, //成功数 "failed": 0 //失败数 }, "_seq_no": 30, //操作序列号 "_primary_term": 1 //主分片的term }搜索文档Match 查询$params = [ 'index' => 'user', //索引名称 'type' => 'user', //类型名称 'body' => [ 'query' => [ 'match' => [ 'username' => 'test', ], ], ], ]; echo json_encode($this->client->search($params));返回结果：{ "took": 23, //查询耗时 "timed_out": false, //是否超时 "_shards": { //分片信息 "total": 3, //分片总数 "successful": 3, //成功数 "skipped": 0, //跳过数 "failed": 0 //失败数 }, "hits": { //查询结果 "total": { //总数 "value": 1, //总数 "relation": "eq" //关系 }, "max_score": 6.800749, //最高分 "hits": [ //结果 { "_index": "user", //索引名称 "_type": "user", //类型名称 "_id": "1", //文档id "_score": 6.800749, //分数 "_source": { //文档内容 "uid": 1, "username": "test", "signature": "test", "phone": "13276535811", "money": "100", "address": "天津 天津市 东丽区", "create_time": 1652340350 } } ] } }bool 查询$params = [ 'index' => 'user', //索引名称 'type' => 'user', //类型名称 'body' => [ 'query' => [ 'bool' => [ 'must' => [ //查询条件 must表示必须满足(相当于and)，should表示可以满足（相当于or） [ 'match' => [ 'username' => '胡' ] ], [ 'match' => [ 'address' => '云' ] ], ] ] ] ] ]; echo json_encode($this->client->search($params));返回结果：{ "took": 896, "timed_out": false, "_shards": { "total": 3, "successful": 3, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 1, "relation": "eq" }, "max_score": 8.003002, "hits": [ { "_index": "user", "_type": "user", "_id": "305", "_score": 8.003002, "_source": { "uid": 305, "username": "李超", "phone": "13574552270", "signature": "新改思所满确无性口区装农斯更员整图动工织备山象革道转正清系电前自物象很度使今经", "money": "15.36", "address": "广东省 惠州市 惠阳区", "creat_time": "2011-04-15 15:43:49" } } ] } }复杂查询$params = [ 'index' => 'user', 'type' => 'user', 'body' => [ 'query' => [ 'bool' => [ 'filter' => [ //过滤,返回符合条件的数据 'term' => [ 'address' => '云南' ] ], 'should' => [ 'match' => [ 'username' => '李' ] ] ] ] ] ]; echo json_encode($this->client->search($params));Scrolling 查询$params = [ 'index' => 'user', 'type' => 'user', 'body' => [ "query" => [ "match_all" => new \stdClass() ], 'size' => 5 //查询数量 ] ]; echo json_encode($this->client->search($params)); while (isset($response['hits']['hits']) && count($response['hits']['hits']) > 0) { 判断是否还有下一页 $scroll_id = $response['_scroll_id']; //这个是上一次请求返回的scroll_id $response = $this->client->scroll([ //这个是滚动查询 "scroll_id" => $scroll_id, //上一次请求返回的scroll_id "scroll" => "30s" //滚动时间 ] ); }删除文档$params = [ 'index' => 'user', //索引名称 'type' => 'user', //类型名称 'id' => '1', //文档id ]; echo json_encode($this->client->delete($params));返回结果：{ "_index": "user", // 索引名称 "_type": "user", // 类型名称 "_id": "1", // 文档id "_version": 3, // 版本号 "result": "deleted", // 操作结果 "_shards": { // 分片信息 "total": 3, // 分片总数 "successful": 3, // 成功数 "failed": 0 // 失败数 }, // 分片信息 "_seq_no": 309, // 操作序列号 "_primary_term": 1 // 主分片的term }忽略异常这种会忽略 404 异常$params = [ 'index' => 'user', //索引名称 'type' => 'user', //类型名称 'id' => '1', //文档id 'client' => [ 'ignore' => 404 ], //忽略异常 ]; echo json_encode($this->client->get($params)); 返回结果：{ "_index": "user", "_type": "user", "_id": "1", "found": false }这里BadRequest400Exception 和 MissingDocument404Exception 都会被忽略：$params = [ 'index' => 'user', //索引名称 'type' => 'user', //类型名称 'id' => '1', //文档id 'client' => [ 'ignore' => [400, 404] ], //忽略异常 ]; echo json_encode($this->client->get($params));返回结果：{ "_index": "user", "_type": "user", "_id": "1", "found": false }返回详细输出$params = [ 'index' => 'user', //索引名称 'type' => 'user', //类型名称 'id' => '1', //文档id 'client' => [ 'trace' => true ], //返回详细输出 ]; echo json_encode($this->client->get($params));返回结果：原来的返回结果是这样的：{ "_index": "user", "_type": "user", "_id": "5", "_version": 1, "_seq_no": 0, "_primary_term": 1, "found": true, "_source": { "uid": 5, "username": "曾杰", "phone": "13215426458", "signature": "老和际不日强老理县治件京济划热选影江例事导还开点深际建起厂党方速识来当西住原清处维安价油些", "money": "30.37", "address": "澳门特别行政区 离岛 -", "creat_time": "1996-10-06 18:37:13" } }但是加了一个trace字段，用于输出详细输出{ "transfer_stats": { //传输统计 "url": "http://localhost/user/user/5", //请求url "content_type": "application/json; charset=UTF-8", //请求内容类型 "http_code": 200, //请求状态码 "header_size": 282, //请求头大小 "request_size": 163, //请求体大小 "filetime": -1, //文件时间 "ssl_verify_result": 0, //ssl验证结果 "redirect_count": 0, //重定向次数 "total_time": 0.001899, //总时间 "namelookup_time": 0.000505, //域名解析时间 "connect_time": 0.000615, //连接时间 "pretransfer_time": 0.000635, //预传输时间 "size_upload": 0, //上传大小 "size_download": 572, //下载大小 "speed_download": 572000, //下载速度 "speed_upload": 0, //上传速度 "download_content_length": 572, //下载内容长度 "upload_content_length": -1, //上传内容长度 "starttransfer_time": 0.001882, //开始传输时间 "redirect_time": 0, //重定向时间 "redirect_url": "", //重定向url "primary_ip": "::1", //主ip "certinfo": [ //证书信息 ], "primary_port": 1003, //主端口 "local_ip": "::1", //本地ip "local_port": 54994, //本地端口 "http_version": 2, //http版本 "protocol": 1, //协议 "ssl_verifyresult": 0, //ssl验证结果 "scheme": "HTTP", //协议 "appconnect_time_us": 0, //app连接时间 "connect_time_us": 615, //连接时间 "namelookup_time_us": 505, //域名解析时间 "pretransfer_time_us": 635, //预传输时间 "redirect_time_us": 0, //重定向时间 "starttransfer_time_us": 1882, //开始传输时间 "total_time_us": 1899, //总时间 "error": "", //错误信息 "errno": 0 //错误码 }, "curl": { //curl信息 "error": "", //错误信息 "errno": 0 //错误码 }, "effective_url": "http://localhost/user/user/5", //有效url "headers": { //请求头 "Warning": [ //警告 "299 Elasticsearch-7.8.0-757314695644ea9a1dc2fecd26d1a43856725e65 \"[types removal] Specifying types in document get requests is deprecated, use the /{index}/_doc/{id} endpoint instead.\"" //警告信息 ], "content-type": [ //内容类型 "application/json; charset=UTF-8" //内容类型 ], "content-length": [ //内容长度 "572" //内容长度 ] }, "version": "1.1", //版本 "status": 200, //状态码 "reason": "OK", //状态码说明 "body": { //返回内容 "_index": "user", //索引 "_type": "user", //类型 "_id": "5", //id "_version": 1, //版本 "_seq_no": 0, //序列号 "_primary_term": 1, //主键 "found": true, //是否找到 "_source": { //内容 "uid": 5, "username": "曾杰", "phone": "13215426458", "signature": "老和际不日强老理县治件京济划热选影江例事导还开点深际建起厂党方速识来当西住原清处维安价油些", "money": "30.37", "address": "澳门特别行政区 离岛 -", "creat_time": "1996-10-06 18:37:13" } } }PHP 处理 JSON 数组或对象空对象{ "query" : { "match" : { "content" : "quick brown fox" } }, "highlight" : { "fields" : { "content" : {} //这个空对象便会引起问题, 因为这个空对象会被转换成一个字符串, 并且会被解析成一个数组, 因此会出现问题 } } }改变为：$params['body'] = array( 'query' => array( 'match' => array( 'username' => '默然' ) ), 'highlight' => array( 'fields' => array( 'content' => new \stdClass() //使用PHP stdClass类来代替空对象, 因为这个类不会被转换成字符串, 并且不会被解析成数组, 因此不会出现问题 ) ) ); $results = $this->client->search($params);修改文档部分修改$params = [ 'index' => 'user', 'type' => 'user', 'id' => '3', 'body' => [ 'doc' => [ 'username' => 'ab313131313c', 'money' => '100', ] ] ]; $response = $this->client->update($params); echo json_encode($response); 返回结果：{ "_index": "user", "_type": "user", "_id": "3", "_version": 3, "result": "updated", "_shards": { "total": 3, "successful": 3, "failed": 0 }, "_seq_no": 369, "_primary_term": 1 }
条件查询查询指定字段GET http://localhost:9200/shopping/_search查询所有数据，只显示字段title和price请求体：{ "query":{ "match_all":{} }, "_source":["title","price"] }返回结果：{ "took": 3, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 9, "relation": "eq" }, "max_score": 1, "hits": [ { "_index": "shopping", "_type": "_doc", "_id": "kq3nZIAB6CX3m_v3APT6", "_score": 1, "_source": { "price": 3999, "title": "小米手机" } }, { "_index": "shopping", "_type": "_doc", "_id": "k63tZIAB6CX3m_v3vfQI", "_score": 1, "_source": { "price": 3999, "title": "小米手机" } }, { "_index": "shopping", "_type": "_doc", "_id": "l636ZIAB6CX3m_v3q_R5", "_score": 1, "_source": { "price": 1999, "title": "华为手机" } }, { "_index": "shopping", "_type": "_doc", "_id": "ma37ZIAB6CX3m_v3BvQc", "_score": 1, "_source": { "price": 1999, "title": "华为手机" } }, { "_index": "shopping", "_type": "_doc", "_id": "n60KZYAB6CX3m_v3q_Tc", "_score": 1, "_source": { "price": 3999, "title": "小米手机" } }, { "_index": "shopping", "_type": "_doc", "_id": "oK0KZYAB6CX3m_v3rfQs", "_score": 1, "_source": { "price": 3999, "title": "小米手机" } }, { "_index": "shopping", "_type": "_doc", "_id": "oa0KZYAB6CX3m_v3rvS_", "_score": 1, "_source": { "price": 3999, "title": "小米手机" } }, { "_index": "shopping", "_type": "_doc", "_id": "oq0KZYAB6CX3m_v3sPQR", "_score": 1, "_source": { "price": 3999, "title": "小米手机" } }, { "_index": "shopping", "_type": "_doc", "_id": "o60KZYAB6CX3m_v3sfT8", "_score": 1, "_source": { "price": 3999, "title": "小米手机" } } ] } }分页查询GET http://localhost:9200/shopping/_search请求体：{ "query":{ "match_all":{} }, "from":0, "size":2 }返回结果：{ "took": 2, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 9, "relation": "eq" }, "max_score": 1, "hits": [ { "_index": "shopping", "_type": "_doc", "_id": "kq3nZIAB6CX3m_v3APT6", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "k63tZIAB6CX3m_v3vfQI", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } } ] } }查询排序GET http://localhost:9200/shopping/_search按价格的从高到低排序请求体：{ "query":{ "match_all":{} }, "sort":[ { "price":{ "order":"desc" } } ] }返回结果：{ "took": 13, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 9, "relation": "eq" }, "max_score": null, "hits": [ { "_index": "shopping", "_type": "_doc", "_id": "kq3nZIAB6CX3m_v3APT6", "_score": null, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 }, "sort": [ 3999 ] }, { "_index": "shopping", "_type": "_doc", "_id": "k63tZIAB6CX3m_v3vfQI", "_score": null, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 }, "sort": [ 3999 ] }, { "_index": "shopping", "_type": "_doc", "_id": "n60KZYAB6CX3m_v3q_Tc", "_score": null, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 }, "sort": [ 3999 ] }, { "_index": "shopping", "_type": "_doc", "_id": "oK0KZYAB6CX3m_v3rfQs", "_score": null, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 }, "sort": [ 3999 ] }, { "_index": "shopping", "_type": "_doc", "_id": "oa0KZYAB6CX3m_v3rvS_", "_score": null, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 }, "sort": [ 3999 ] }, { "_index": "shopping", "_type": "_doc", "_id": "oq0KZYAB6CX3m_v3sPQR", "_score": null, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 }, "sort": [ 3999 ] }, { "_index": "shopping", "_type": "_doc", "_id": "o60KZYAB6CX3m_v3sfT8", "_score": null, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 }, "sort": [ 3999 ] }, { "_index": "shopping", "_type": "_doc", "_id": "l636ZIAB6CX3m_v3q_R5", "_score": null, "_source": { "title": "华为手机", "category": "华为", "images": "http://www.gulixueyuan.com/hw.jpg", "price": 1999 }, "sort": [ 1999 ] }, { "_index": "shopping", "_type": "_doc", "_id": "ma37ZIAB6CX3m_v3BvQc", "_score": null, "_source": { "title": "华为手机", "category": "华为", "images": "http://www.gulixueyuan.com/hw.jpg", "price": 1999 }, "sort": [ 1999 ] } ] } }多条件查询GET http://localhost:9200/shopping/_search查询小米的牌子，价格为3999元的手机。请求体：{ "query":{ "bool":{ "must":[{ //must表示必须满足(相当于and)，should表示可以满足（相当于or） "match":{ "category":"小米" } },{ "match":{ "price":3999.00 } }] } } }返回结果：{ "took": 3, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 7, "relation": "eq" }, "max_score": 1.9979823, "hits": [ { "_index": "shopping", "_type": "_doc", "_id": "kq3nZIAB6CX3m_v3APT6", "_score": 1.9979823, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "k63tZIAB6CX3m_v3vfQI", "_score": 1.9979823, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "n60KZYAB6CX3m_v3q_Tc", "_score": 1.9979823, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "oK0KZYAB6CX3m_v3rfQs", "_score": 1.9979823, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "oa0KZYAB6CX3m_v3rvS_", "_score": 1.9979823, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "oq0KZYAB6CX3m_v3sPQR", "_score": 1.9979823, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "o60KZYAB6CX3m_v3sfT8", "_score": 1.9979823, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } } ] } }条件查询列子2GET http://localhost:9200/shopping/_search查询小米和华为的牌子，价格大于3000元的手机。查询范围可以使用以下4个：gt 大于gte 大于或等于lt 小于lte 小于或等于must表示必须满足(相当于and)，should表示可以满足（相当于or）请求体：{ "query":{ "bool":{ "should":[ { "match":{ "category":"小米" } }, { "match":{ "category":"华为" } } ], "filter":{ "range":{ "price":{ "gt":3000 } } } } } }返回结果：{ "took": 2, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 7, "relation": "eq" }, "max_score": 0.99798226, "hits": [ { "_index": "shopping", "_type": "_doc", "_id": "kq3nZIAB6CX3m_v3APT6", "_score": 0.99798226, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "k63tZIAB6CX3m_v3vfQI", "_score": 0.99798226, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "n60KZYAB6CX3m_v3q_Tc", "_score": 0.99798226, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "oK0KZYAB6CX3m_v3rfQs", "_score": 0.99798226, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "oa0KZYAB6CX3m_v3rvS_", "_score": 0.99798226, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "oq0KZYAB6CX3m_v3sPQR", "_score": 0.99798226, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "o60KZYAB6CX3m_v3sfT8", "_score": 0.99798226, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } } ] } }全文检索GET http://localhost:9200/shopping/_search这功能像搜索引擎那样，如品牌输入“小华”，返回结果带回品牌有“小米”和华为的。请求体：{ "query":{ "match":{ "category" : "小华" } } }返回结果：{ "took": 2, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 9, "relation": "eq" }, "max_score": 0.93430924, "hits": [ { "_index": "shopping", "_type": "_doc", "_id": "l636ZIAB6CX3m_v3q_R5", "_score": 0.93430924, "_source": { "title": "华为手机", "category": "华为", "images": "http://www.gulixueyuan.com/hw.jpg", "price": 1999 } }, { "_index": "shopping", "_type": "_doc", "_id": "ma37ZIAB6CX3m_v3BvQc", "_score": 0.93430924, "_source": { "title": "华为手机", "category": "华为", "images": "http://www.gulixueyuan.com/hw.jpg", "price": 1999 } }, { "_index": "shopping", "_type": "_doc", "_id": "kq3nZIAB6CX3m_v3APT6", "_score": 0.49899113, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "k63tZIAB6CX3m_v3vfQI", "_score": 0.49899113, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "n60KZYAB6CX3m_v3q_Tc", "_score": 0.49899113, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "oK0KZYAB6CX3m_v3rfQs", "_score": 0.49899113, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "oa0KZYAB6CX3m_v3rvS_", "_score": 0.49899113, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "oq0KZYAB6CX3m_v3sPQR", "_score": 0.49899113, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "o60KZYAB6CX3m_v3sfT8", "_score": 0.49899113, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } } ] } }完全匹配GET http://localhost:9200/shopping/_search{ "query":{ "match_phrase":{ "category" : "为" } } }返回结果：{ "took": 1, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 2, "relation": "eq" }, "max_score": 0.93430924, "hits": [ { "_index": "shopping", "_type": "_doc", "_id": "l636ZIAB6CX3m_v3q_R5", "_score": 0.93430924, "_source": { "title": "华为手机", "category": "华为", "images": "http://www.gulixueyuan.com/hw.jpg", "price": 1999 } }, { "_index": "shopping", "_type": "_doc", "_id": "ma37ZIAB6CX3m_v3BvQc", "_score": 0.93430924, "_source": { "title": "华为手机", "category": "华为", "images": "http://www.gulixueyuan.com/hw.jpg", "price": 1999 } } ] } }高亮查询GET http://localhost:9200/shopping/_search请求体：{ "query":{ "match_phrase":{ "category" : "为" } }, "highlight":{ "fields":{ "category":{}//<----高亮这字段 } } }返回结果：{ "took": 19, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 2, "relation": "eq" }, "max_score": 0.93430924, "hits": [ { "_index": "shopping", "_type": "_doc", "_id": "l636ZIAB6CX3m_v3q_R5", "_score": 0.93430924, "_source": { "title": "华为手机", "category": "华为", "images": "http://www.gulixueyuan.com/hw.jpg", "price": 1999 }, "highlight": { "category": [ "华为" ] } }, { "_index": "shopping", "_type": "_doc", "_id": "ma37ZIAB6CX3m_v3BvQc", "_score": 0.93430924, "_source": { "title": "华为手机", "category": "华为", "images": "http://www.gulixueyuan.com/hw.jpg", "price": 1999 }, "highlight": { "category": [ "华为" //<------高亮一个为字。 ] } } ] } }聚合查询分组查询GET http://localhost:9200/shopping/_search类似与关系型数据库中的 group by，当然还有很多其他的聚合，例如取最大值max、平均值avg等等。接下来按price字段进行分组：请求体：{ "aggs":{//聚合操作 "price_group":{//名称，随意起名 "terms":{//分组 "field":"price"//分组字段 } } } }返回结果：{ "took": 11, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 9, "relation": "eq" }, "max_score": 1, "hits": [ { "_index": "shopping", "_type": "_doc", "_id": "kq3nZIAB6CX3m_v3APT6", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "k63tZIAB6CX3m_v3vfQI", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "l636ZIAB6CX3m_v3q_R5", "_score": 1, "_source": { "title": "华为手机", "category": "华为", "images": "http://www.gulixueyuan.com/hw.jpg", "price": 1999 } }, { "_index": "shopping", "_type": "_doc", "_id": "ma37ZIAB6CX3m_v3BvQc", "_score": 1, "_source": { "title": "华为手机", "category": "华为", "images": "http://www.gulixueyuan.com/hw.jpg", "price": 1999 } }, { "_index": "shopping", "_type": "_doc", "_id": "n60KZYAB6CX3m_v3q_Tc", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "oK0KZYAB6CX3m_v3rfQs", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "oa0KZYAB6CX3m_v3rvS_", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "oq0KZYAB6CX3m_v3sPQR", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "o60KZYAB6CX3m_v3sfT8", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } } ] }, "aggregations": { "price_group": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": 3999, "doc_count": 7 }, { "key": 1999, "doc_count": 2 } ] } } }上面返回结果会附带原始数据的。若不想要不附带原始数据的结果，可以使用下面的方式：请求体：{ "aggs":{ "price_group":{ "terms":{ "field":"price" } } }, "size":0 }返回结果：{ "took": 4, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 9, "relation": "eq" }, "max_score": null, "hits": [] }, "aggregations": { "price_group": { "doc_count_error_upper_bound": 0, "sum_other_doc_count": 0, "buckets": [ { "key": 3999, "doc_count": 7 }, { "key": 1999, "doc_count": 2 } ] } } }平均值GET所有手机价格求平均值。请求体：{ "aggs":{ "price_avg":{//名称，随意起名 "avg":{//求平均 "field":"price" } } }, "size":0 }返回结果：{ "took": 2, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 9, "relation": "eq" }, "max_score": null, "hits": [] }, "aggregations": { "price_avg": { "value": 3554.5555555555557 } } }
数据格式Elasticsearch是面向文档型数据库，一条数据在这里就是一个文档。 为了方便大家理解，我们将 Elasticsearch 里存储文档数据和关系型数据库 MySQL 存储数据的概念进行一个类比ES 里的 Index 可以看做一个库，而 Types 相当于表， Documents 则相当于表的行。这里 Types 的概念已经被逐渐弱化， Elasticsearch 6.X 中，一个 index 下已经只能包含一个type， Elasticsearch 7.X 中, Type 的概念已经被删除了。创建索引PUT http://localhost:9200/shopping{ "acknowledged": true, "shards_acknowledged": true, "index": "shopping" }查看当前索引GET http://localhost:9200/shopping{ "shopping": {//索引名 "aliases": {},//别名 "mappings": {},//映射 "settings": {//设置 "index": {//设置 - 索引 "creation_date": "1650959730840",//设置 - 索引 - 创建时间 "number_of_shards": "1",//设置 - 索引 - 主分片数量 "number_of_replicas": "1",//设置 - 索引 - 主分片数量 "uuid": "Y2GAupofQFiHc5nsAlDe1w",//设置 - 索引 - 主分片数量 "version": {//设置 - 索引 - 主分片数量 "created": "7080099" }, "provided_name": "shopping"//设置 - 索引 - 主分片数量 } } } }查看当前ES中所有的索引GET http://localhost:9200/_cat/indices?vhealth status index uuid pri rep docs.count docs.deleted store.size pri.store.size yellow open shopping Y2GAupofQFiHc5nsAlDe1w 1 1 0 0 208b 208b表头含义health当前服务器健康状态： green(集群完整) yellow(单点正常、集群不完整) red(单点不正常)status索引打开、关闭状态index索引名uuid索引统一编号pri主分片数量rep副本数量docs.count可用文档数量docs.deleted文档删除状态（逻辑删除）store.size主分片和副分片整体占空间大小pri.store.size主分片占空间大小删除索引DELETE http://localhost:9200/shopping{ "acknowledged": true }增加文档POST http://localhost:9200/shopping/_doc请求体JSON内容为：{ "title":"小米手机", "category":"小米", "images":"http://www.gulixueyuan.com/xm.jpg", "price":3999.00 }注意，此处发送请求的方式必须为 POST，不能是 PUT，否则会发生错误 。返回结果：{ "_index": "shopping", "_type": "_doc", "_id": "k63tZIAB6CX3m_v3vfQI", "_version": 1, "result": "created", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 3, "_primary_term": 1 }上面的数据创建后，由于没有指定数据唯一性标识（ID），默认情况下， ES 服务器会随机生成一个。如果想要自定义唯一性标识，需要在创建时指定： http://127.0.0.1:9200/shopping/_doc/1001，这样就可以指定 ID 为 1001 。{ "_index": "shopping", "_type": "_doc", "_id": "1001", //自定义唯一ID标识 "_version": 3, "result": "updated", "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 4, "_primary_term": 1 }此处需要注意：如果增加数据时明确数据主键，那么请求方式也可以为 PUT。查询文档通过主键ID查询文档：GET http://localhost:9200/shopping/_doc/1001{ "_index": "shopping", "_type": "_doc", "_id": "1001", "_version": 3, "_seq_no": 4, "_primary_term": 1, "found": true, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }查询全部文档：GET http://localhost:9200/shopping/_search{ "took": 2, //查询花费时长（毫秒） "timed_out": false, // 请求是否超时 "_shards": { //搜索了多少分片，成功、失败或者跳过了多个分片（明细） "total": 1, //总分片数 "successful": 1, //成功分片数 "skipped": 0, //失败分片数 "failed": 0 // 跳过分片数 }, "hits": { "total": { "value": 3, // 找到的文档总数 "relation": "eq" }, "max_score": 1, 最相关的文档分数 "hits": [ { "_index": "shopping", "_type": "_doc", "_id": "kq3nZIAB6CX3m_v3APT6", "_score": 1, //文档的相关性算分 (match_all 没有算分) "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "k63tZIAB6CX3m_v3vfQI", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "1001", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } } ] } }更新文档全局更新POST http://localhost:9200/shopping/_doc/1001请求JSON数据：{ "title":"华为手机", "category":"华为", "images":"http://www.gulixueyuan.com/hw.jpg", "price":1999.00 }返回结果：{ "_index": "shopping", "_type": "_doc", "_id": "1001", "_version": 10, "result": "updated", //updated 表示数据被更新 "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 13, "_primary_term": 1 }局部更新PUT http://localhost:9200/shopping/_update/1001请求JSON数据：{ "doc": { "title":"小米手机", "category":"小米" } }返回结果：{ "_index": "shopping", "_type": "_doc", "_id": "1001", "_version": 11, "result": "updated", //updated 表示数据被更新 "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 14, "_primary_term": 1 }删除文档DELETE http://localhost:9200/shopping/_doc/1001返回结果：{ "_index": "shopping", "_type": "_doc", "_id": "1001", "_version": 12, "result": "deleted", // deleted 表示数据被删除 "_shards": { "total": 2, "successful": 1, "failed": 0 }, "_seq_no": 15, "_primary_term": 1 }查询文档查询全部GET http://localhost:9200/shopping/_search返回结果数据：{ "took": 1, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 4, "relation": "eq" }, "max_score": 1, "hits": [ { "_index": "shopping", "_type": "_doc", "_id": "kq3nZIAB6CX3m_v3APT6", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "k63tZIAB6CX3m_v3vfQI", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "l636ZIAB6CX3m_v3q_R5", "_score": 1, "_source": { "title": "华为手机", "category": "华为", "images": "http://www.gulixueyuan.com/hw.jpg", "price": 1999 } }, { "_index": "shopping", "_type": "_doc", "_id": "ma37ZIAB6CX3m_v3BvQc", "_score": 1, "_source": { "title": "华为手机", "category": "华为", "images": "http://www.gulixueyuan.com/hw.jpg", "price": 1999 } } ] } }按条件查询(URL带参查询)GET http://localhost:9200/shopping/_search?q=category:小米返回结果：{ "took": 19, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 2, "relation": "eq" }, "max_score": 1.8889232, "hits": [ { "_index": "shopping", "_type": "_doc", "_id": "kq3nZIAB6CX3m_v3APT6", "_score": 1.8889232, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "k63tZIAB6CX3m_v3vfQI", "_score": 1.8889232, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } } ] } }按条件查询（请求体带参查询）POST http://localhost:9200/shopping/_search请求体：{ "query": { "match": { "category": "小米" } } }返回结果：{ "took": 1, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 7, "relation": "eq" }, "max_score": 0.99798226, "hits": [ { "_index": "shopping", "_type": "_doc", "_id": "kq3nZIAB6CX3m_v3APT6", "_score": 0.99798226, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "k63tZIAB6CX3m_v3vfQI", "_score": 0.99798226, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "n60KZYAB6CX3m_v3q_Tc", "_score": 0.99798226, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "oK0KZYAB6CX3m_v3rfQs", "_score": 0.99798226, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "oa0KZYAB6CX3m_v3rvS_", "_score": 0.99798226, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "oq0KZYAB6CX3m_v3sPQR", "_score": 0.99798226, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "o60KZYAB6CX3m_v3sfT8", "_score": 0.99798226, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } } ] } }查询全部数据（请求体带参查询）POST http://localhost:9200/shopping/_search请求体：{ "query": { "match_all": {} } }等同于下面此接口GET http://127.0.0.1:9200/shopping/_search返回结果：{ "took": 1, "timed_out": false, "_shards": { "total": 1, "successful": 1, "skipped": 0, "failed": 0 }, "hits": { "total": { "value": 9, "relation": "eq" }, "max_score": 1, "hits": [ { "_index": "shopping", "_type": "_doc", "_id": "kq3nZIAB6CX3m_v3APT6", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "k63tZIAB6CX3m_v3vfQI", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "l636ZIAB6CX3m_v3q_R5", "_score": 1, "_source": { "title": "华为手机", "category": "华为", "images": "http://www.gulixueyuan.com/hw.jpg", "price": 1999 } }, { "_index": "shopping", "_type": "_doc", "_id": "ma37ZIAB6CX3m_v3BvQc", "_score": 1, "_source": { "title": "华为手机", "category": "华为", "images": "http://www.gulixueyuan.com/hw.jpg", "price": 1999 } }, { "_index": "shopping", "_type": "_doc", "_id": "n60KZYAB6CX3m_v3q_Tc", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "oK0KZYAB6CX3m_v3rfQs", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "oa0KZYAB6CX3m_v3rvS_", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "oq0KZYAB6CX3m_v3sPQR", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } }, { "_index": "shopping", "_type": "_doc", "_id": "o60KZYAB6CX3m_v3sfT8", "_score": 1, "_source": { "title": "小米手机", "category": "小米", "images": "http://www.gulixueyuan.com/xm.jpg", "price": 3999 } } ] } }
今天弄自己项目的时候，本地全部正常，当我部署到服务器上的时候就报了这样的错误，致命错误: Call to undefined function think\response\finfo_open()后面排查了一下，原来是服务的php扩展没安装，我用的宝塔，所以就说下宝塔怎么安装！我们先看一下项目的php版本，然后去软件商店找到相对应的php版本点开设置，安装这个fileinfo这个扩展然后项目就正常了！！
今天早上来公司，就开始了学习elasticsearch，结果万万没想到，直接是一波三折呀，才把这个启动起来。先从官网下载压缩包解压后得到这几个文件夹详解：目录名称介绍bin二进制脚本，包含启动命令和安装插件命令等config配置文件目录lib依赖包目录logs日志文件目录modules模块库plugins插件目录data数据储存目录然后点击启动bin目录下的elasticsearch.bat启动，然后我的就变成了这样就一直再解决，最后修改了elasticsearch.yml才得以成功访问修改配置注意：9300端口为Elasticsearch集群间组件的通信端口，9200端口为浏览器访问的http协议RESTful端口。把有几个的true改为false就OK了最后来安装个插件试试安装插件我们先来看看有无插件（本机）执行命令 elasticsearch-plugin list然后安装个analysis-icu插件试试执行 elasticsearch-plugin install analysis-icu这样就安装成功了再来用哪个list命令浏览器查看（http://127.0.0.1:9200/_cat/plugins）好了 完了 继续学习！！！
今天看了下PhpSpreadsheet 的使用，以前只看过phpExcel相关的，这里的数据全是随机生成的，生成代码在下方,不必要看代码，就一个思路，哈哈哈，大佬绕过！连接数据库(conn.php)<?php $servername = "localhost"; $username = "root"; $password = "123456"; $database = "hotel"; // 创建连接 $conn = mysqli_connect($servername, $username, $password, $database); // 检测连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } //echo "连接成功"; 首页(index.php)<?php require_once "./conn.php"; ?> 首页 导出 导入 序号 账号 姓名 年龄 性别 创建时间 <?php $sql = "select * from test"; $result = mysqli_query($conn,$sql); while ($rows = mysqli_fetch_array($result)) { echo " $rows[0] "; echo " $rows[1] "; echo " $rows[2] "; echo " $rows[3] "; echo " $rows[4] "; echo " $rows[5] "; } ?> 生成名字(name.php)用了某个大老的 翻不到谁的了 等我再找找 找到补上连接<?php class rndChinaName { private $arrXing, $numbXing; private $arrMing, $numbMing; function rndChinaName() { $this->getXingList(); $this->getMingList(); } /* 获取姓列表 */ private function getXingList() { $this->arrXing = array( '赵', '钱', '孙', '李', '周', '吴', '郑', '王', '冯', '陈', '褚', '卫', '蒋', '沈', '韩', '杨', '朱', '秦', '尤', '许', '何', '吕', '施', '张', '孔', '曹', '严', '华', '金', '魏', '陶', '姜', '戚', '谢', '邹', '喻', '柏', '水', '窦', '章', '云', '苏', '潘', '葛', '奚', '范', '彭', '郎', '鲁', '韦', '昌', '马', '苗', '凤', '花', '方', '任', '袁', '柳', '鲍', '史', '唐', '费', '薛', '雷', '贺', '倪', '汤', '滕', '殷', '罗', '毕', '郝', '安', '常', '傅', '卞', '齐', '元', '顾', '孟', '平', '黄', '穆', '萧', '尹', '姚', '邵', '湛', '汪', '祁', '毛', '狄', '米', '伏', '成', '戴', '谈', '宋', '茅', '庞', '熊', '纪', '舒', '屈', '项', '祝', '董', '梁', '杜', '阮', '蓝', '闵', '季', '贾', '路', '娄', '江', '童', '颜', '郭', '梅', '盛', '林', '钟', '徐', '邱', '骆', '高', '夏', '蔡', '田', '樊', '胡', '凌', '霍', '虞', '万', '支', '柯', '管', '卢', '莫', '柯', '房', '裘', '缪', '解', '应', '宗', '丁', '宣', '邓', '单', '杭', '洪', '包', '诸', '左', '石', '崔', '吉', '龚', '程', '嵇', '邢', '裴', '陆', '荣', '翁', '荀', '于', '惠', '甄', '曲', '封', '储', '仲', '伊', '宁', '仇', '甘', '武', '符', '刘', '景', '詹', '龙', '叶', '幸', '司', '黎', '溥', '印', '怀', '蒲', '邰', '从', '索', '赖', '卓', '屠', '池', '乔', '胥', '闻', '莘', '党', '翟', '谭', '贡', '劳', '逄', '姬', '申', '扶', '堵', '冉', '宰', '雍', '桑', '寿', '通', '燕', '浦', '尚', '农', '温', '别', '庄', '晏', '柴', '瞿', '阎', '连', '习', '容', '向', '古', '易', '廖', '庾', '终', '步', '都', '耿', '满', '弘', '匡', '国', '文', '寇', '广', '禄', '阙', '东', '欧', '利', '师', '巩', '聂', '关', '荆', '司马', '上官', '欧阳', '夏侯', '诸葛', '闻人', '东方', '赫连', '皇甫', '尉迟', '公羊', '澹台', '公冶', '宗政', '濮阳', '淳于', '单于', '太叔', '申屠', '公孙', '仲孙', '轩辕', '令狐', '徐离', '宇文', '长孙', '慕容', '司徒', '司空' ); $this->numbXing = count($this->arrXing); //姓总数 } /* 获取名列表 */ private function getMingList() { $this->arrMing = array( '伟', '刚', '勇', '毅', '俊', '峰', '强', '军', '平', '保', '东', '文', '辉', '力', '明', '永', '健', '世', '广', '志', '义', '兴', '良', '海', '山', '仁', '波', '宁', '贵', '福', '生', '龙', '元', '全', '国', '胜', '学', '祥', '才', '发', '武', '新', '利', '清', '飞', '彬', '富', '顺', '信', '子', '杰', '涛', '昌', '成', '康', '星', '光', '天', '达', '安', '岩', '中', '茂', '进', '林', '有', '坚', '和', '彪', '博', '诚', '先', '敬', '震', '振', '壮', '会', '思', '群', '豪', '心', '邦', '承', '乐', '绍', '功', '松', '善', '厚', '庆', '磊', '民', '友', '裕', '河', '哲', '江', '超', '浩', '亮', '政', '谦', '亨', '奇', '固', '之', '轮', '翰', '朗', '伯', '宏', '言', '若', '鸣', '朋', '斌', '梁', '栋', '维', '启', '克', '伦', '翔', '旭', '鹏', '泽', '晨', '辰', '士', '以', '建', '家', '致', '树', '炎', '德', '行', '时', '泰', '盛', '雄', '琛', '钧', '冠', '策', '腾', '楠', '榕', '风', '航', '弘', '秀', '娟', '英', '华', '慧', '巧', '美', '娜', '静', '淑', '惠', '珠', '翠', '雅', '芝', '玉', '萍', '红', '娥', '玲', '芬', '芳', '燕', '彩', '春', '菊', '兰', '凤', '洁', '梅', '琳', '素', '云', '莲', '真', '环', '雪', '荣', '爱', '妹', '霞', '香', '月', '莺', '媛', '艳', '瑞', '凡', '佳', '嘉', '琼', '勤', '珍', '贞', '莉', '桂', '娣', '叶', '璧', '璐', '娅', '琦', '晶', '妍', '茜', '秋', '珊', '莎', '锦', '黛', '青', '倩', '婷', '姣', '婉', '娴', '瑾', '颖', '露', '瑶', '怡', '婵', '雁', '蓓', '纨', '仪', '荷', '丹', '蓉', '眉', '君', '琴', '蕊', '薇', '菁', '梦', '岚', '苑', '婕', '馨', '瑗', '琰', '韵', '融', '园', '艺', '咏', '卿', '聪', '澜', '纯', '毓', '悦', '昭', '冰', '爽', '琬', '茗', '羽', '希', '欣', '飘', '育', '滢', '馥', '筠', '柔', '竹', '霭', '凝', '晓', '欢', '霄', '枫', '芸', '菲', '寒', '伊', '亚', '宜', '可', '姬', '舒', '影', '荔', '枝', '丽', '阳', '妮', '宝', '贝', '初', '程', '梵', '罡', '恒', '鸿', '桦', '骅', '剑', '娇', '纪', '宽', '苛', '灵', '玛', '媚', '琪', '晴', '容', '睿', '烁', '堂', '唯', '威', '韦', '雯', '苇', '萱', '阅', '彦', '宇', '雨', '洋', '忠', '宗', '曼', '紫', '逸', '贤', '蝶', '菡', '绿', '蓝', '儿', '翠', '烟', '小', '轩' ); //名总数 $this->numbMing = count($this->arrMing); } // 获取姓 private function getXing() { // mt_rand() 比rand()方法快四倍，而且生成的随机数比rand()生成的伪随机数无规律。 return $this->arrXing[mt_rand(0, $this->numbXing - 1)]; } // 获取名字 private function getMing() { return $this->arrMing[mt_rand(0, $this->numbMing - 1)]; } // 获取名字 public function getName($type = 0) { $name = ''; switch ($type) { case 1: //2字 $name = $this->getXing() . $this->getMing(); break; case 2: //随机2、3个字 $name = $this->getXing() . $this->getMing(); if (mt_rand(0, 100) > 50) $name .= $this->getMing(); break; case 3: //只取姓 $name = $this->getXing(); break; case 4: //只取名 $name = $this->getMing(); break; case 0: default: //默认情况 1姓+2名 $name = $this->getXing() . $this->getMing() . $this->getMing(); } return $name; } } 添加数据到数据库(while.php) /** * @param $num 数据条数 */ getdata(100); function getdata($num) { require './conn.php'; require 'name.php'; for ($a = 0; $a < $num; $a++) { //随机生成姓名 $name_obj = new rndChinaName(); $nickname = $name_obj->getName(2); //随机输出男女 $my_array = ['男', '女']; $sex = $my_array[rand(0, 1)]; //随机年龄 $age = rand(10, 50); //随机name $characters = 'abcdefghijklmnopqrstuvwxyz'; $name = ''; for ($i = 0; $i < 6; $i++) { $index = rand(0, strlen($characters) - 1); $name .= $characters[$index]; } //添加时间 $creattime = date("Y-m-d H:i:s",time()); $sql = "insert into test(name,nickname,sex,age,creattime) values ('$name','$nickname','$sex','$age','$creattime')"; $res = $conn->query($sql); if (!$res) { echo $a . '添加失败 '; } else { echo $a . '添加成功 '; } } }导出数据(exportdown.php)<?php require __DIR__.'/conn.php'; $sql = "select * from test"; $result = mysqli_query($conn,$sql); $rows = mysqli_fetch_all($result); # 载入 autoload require_once __DIR__.'/vendor/autoload.php'; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; $spreadsheet=new Spreadsheet(); $sheet=$spreadsheet->getActiveSheet(); //设置标题 $sheet ->setCellValue('A1','ID'); $sheet ->setCellValue('B1','账号'); $sheet ->setCellValue('C1','姓名'); $sheet ->setCellValue('D1','性别'); $sheet ->setCellValue('E1','年龄'); $sheet ->setCellValue('F1','创建时间'); //设置表内数据 $sheet->fromArray( $rows, null, 'A2' ); //MIME 协议，文件的类型，不设置，会默认html header('Content-Type:application/vnd.ms-execl'); //MIME 协议的扩展 header('Content-Disposition:attachment;filename=下载.xls'); //缓存控制 header('Cache-Control:max-age=0'); $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet,'Xlsx'); // php://output 它是一个只写数据流，允许你以 print 和 echo 一样的方式写入到输出缓冲区。 $writer->save('php://output'); 导入数据<?php //print_r($_FILES); $file = $_FILES['file']['tmp_name']; //载入composer自动加载文件 require_once __DIR__.'/vendor/autoload.php'; //载入方法库 require 'conn.php'; //创建读操作 $reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader('Xlsx'); //打开文件、载入execl表格 $spreadsheet = $reader->load($file); //获取活动工作簿 $sheet=$spreadsheet->getActiveSheet(); //获取总列数 $highestColum = $sheet->getHighestColumn(); //获取总行数 $highestRow = $sheet->getHighestRow(); //列数 改为数字显示 $highestColumIndex = \PhpOffice\PhpSpreadsheet\Cell\Coordinate::columnIndexFromString($highestColum); $log =[]; for($a=2;$a<$highestRow;$a++){ $name = $sheet->getCellByColumnAndRow(1,$a)->getValue(); $nickname = $sheet->getCellByColumnAndRow(2,$a)->getValue(); $sex = $sheet->getCellByColumnAndRow(3,$a)->getValue(); $age = $sheet->getCellByColumnAndRow(4,$a)->getValue(); $creattime = date('Y-m-d H:i:s',time()); $add = "insert into test(name,nickname,sex,age,creattime) values ('$name','$nickname','$sex','$age','$creattime')"; $res = $conn->query($add); if($res){ $log[] ='第'.$a.'条插入成功'; }else{ $log[] ='第'.$a.'条插入失败'; } } echo json_encode(['code'=>200,'msg'=>'成功','data'=>array('log'=>$log)]); ?>后缀对应的 content-type表头表头后缀MIME Type.docapplication/msword.dotapplication/msword.docxapplication/vnd.openxmlformats-officedocument.wordprocessingml.document.dotxapplication/vnd.openxmlformats-officedocument.wordprocessingml.template.docmapplication/vnd.ms-word.document.macroEnabled.12.dotmapplication/vnd.ms-word.template.macroEnabled.12.xlsapplication/vnd.ms-excel.xltapplication/vnd.ms-excel.xlaapplication/vnd.ms-excel.xlsxapplication/vnd.openxmlformats-officedocument.spreadsheetml.sheet.xltxapplication/vnd.openxmlformats-officedocument.spreadsheetml.template.xlsmapplication/vnd.ms-excel.sheet.macroEnabled.12.xltmapplication/vnd.ms-excel.template.macroEnabled.12.xlamapplication/vnd.ms-excel.addin.macroEnabled.12.xlsbapplication/vnd.ms-excel.sheet.binary.macroEnabled.12.pptapplication/vnd.ms-powerpoint.potapplication/vnd.ms-powerpoint.ppsapplication/vnd.ms-powerpoint.ppaapplication/vnd.ms-powerpoint.pptxapplication/vnd.openxmlformats-officedocument.presentationml.presentation.potxapplication/vnd.openxmlformats-officedocument.presentationml.template.ppsxapplication/vnd.openxmlformats-officedocument.presentationml.slideshow.ppamapplication/vnd.ms-powerpoint.addin.macroEnabled.12.pptmapplication/vnd.ms-powerpoint.presentation.macroEnabled.12.potmapplication/vnd.ms-powerpoint.presentation.macroEnabled.12.ppsmapplication/vnd.ms-powerpoint.slideshow.macroEnabled.12
宝塔安装git，实现实时更新服务器代码
这几天一直在更新默然iapp后台管理系统，群友们都说弄个在线更新，一直没有思路，后面想到我就是利用git上传的呀，服务端也可以用git呀，然后就有了这篇文章。一、服务端安装gityum install -y git接下来，我们来验证下安装成功没，直接输入git就可以了出现上面这个就是安装成功了这样查看版本号git version配置git信息接下来配置自己的git信息git config --global user.name "your name" git config --global user.email "you email"我们必须创建公钥才能拉去里面的代码ssh-keygen -C "your email" -t rsa一直回车就可以了然后这样查看公钥cat /root/.ssh/id_rsa.pub把公钥复制，配置到gitee上gitee位置：配置完后可以用这个命令测试下：ssh -T git@gitee.com这样就配置完成了，是不是很简单呢，那下面我们来拉代码！git clone https://gitee.com/morannb/moranht.git然后把刚才下载的源码所有文件移动到你的站点目录下，liunx服务器切换目录到站点目录下输入git pull如果gitee端没有任何更新，则向先下面这样有更新的话，则是下图：好了 大功完成了 记住一定不能删除.git文件夹以后直接输入git pull 就完成更新了 记得一定要在有.git那个目录下，但是也有弊端，要重新输入账号密码