ELASTIC 搜索开发实战-笔记(2)

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS PostgreSQL,高可用系列 2核4GB
Elasticsearch Serverless通用抵扣包,测试体验金 200元
简介: ELASTIC 搜索开发实战-笔记

搜索示例

数据准备

创建表

CREATE TABLE `blog` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键id',
  `title` varchar(60) DEFAULT NULL COMMENT '标题',
  `author` varchar(60) DEFAULT NULL COMMENT '作者',
  `content` text COMMENT '内容',
  `create_time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  `update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8mb4


获取测试数据

# -*- coding: utf-8 -*-
from pprint import pprint
import requests
from parsel import Selector
from puremysql import PureMysql
def get_data(url):
    """
    获取古诗文网数据
    eg: https://www.gushiwen.cn/
    :return: list
    """
    response = requests.get(url)
    sel = Selector(text=response.text)
    rows = sel.css(".main3 .left .sons")
    lst = []
    for row in rows:
        title = row.css("b::text").extract_first()
        author = row.css(".source").xpath("string(.)").extract_first()
        content = row.css(".contson").xpath("string(.)").extract_first()
        if not title:
            continue
        item = {
            "title": title.strip(),
            "author": author.strip(),
            "content": content.replace('\n', ''),
        }
        pprint(item)
        lst.append(item)
    return lst
def insert_data(lst):
    """
    数据入库
    """
    con = PureMysql(db_url="mysql://root:123456@127.0.0.1:3306/data?charset=utf8")
    table = con.table("blog")
    ret = table.insert(lst)
    con.close()
    print("成功入库", ret)
def main():
    # url = "https://www.gushiwen.cn/"
    for page in range(1, 11):
        url = f"https://www.gushiwen.cn/default.aspx?page={page}"
        lst = get_data(url)
        insert_data(lst)
if __name__ == '__main__':
    main()


logstash同步数据配置

config/jdbc.conf

input {
  jdbc {
    jdbc_driver_library => "mysql-connector-java-8.0.16.jar"
    jdbc_driver_class => "com.mysql.cj.jdbc.Driver"
    jdbc_connection_string => "jdbc:mysql://127.0.0.1:3306/data"
    jdbc_user => "root"
    jdbc_password => "123456"
    statement => "SELECT id, title, content, author, create_time, update_time FROM blog"
    jdbc_paging_enabled => "true"
    jdbc_page_size => "5000"
  }
}
filter {
}
output {
  stdout {
    codec => rubydebug
  }
  elasticsearch {
    index => "blog",
    document_id => "%{id}"
  }
}


同步数据

# 检查配置文件
$ ./bin/logstash -t -f config/jdbc.conf
# 执行配置文件
$ ./bin/logstash -f config/jdbc.conf


问题及处理

处理elasticsearch跨域问题

config/elasticsearch.yml


http.cors.enabled: true

http.cors.allow-origin: "*"


搜索提示

高亮结果显示

POST /blog/_search
{
  "query": {
    "match": {
      "author": "李白"
    }
  },
  "highlight": {
    "fields": {
      "author": {}
    }
  }
}


搜索模板

将查询和参数分离

POST /blog/_search/template
{
  "source": {
    "query": {
      "match": {
        "{{key}}": "{{value}}"
      }
    },
    "size": "{{size}}"
  },
  "params": {
    "key": "author",
    "value": "李白",
    "size": 10
  }
}

其他语句

# 调试模板渲染结果: 
GET _render/template
# 取回模板定义的语法: 
GET _scripts/<templatename>
# 删除模板定义的语法: 
DELETE _scripts/<templatename>


创建模板


POST /_scripts/blog_template_v1
{
  "script": {
    "lang": "mustache",
    "source": {
      "query": {
        "match": {
          "{{key}}": "{{value}}"
        }
      },
      "highlight": {
        "fields": {
          "{{key}}": {}
        }
      },
      "size": "{{size}}"
    }
  }
}


使用模板

POST /blog/_search/template
{
  "id": "blog_template_v1",
  "params": {
    "key": "author",
    "value": "李白",
    "size": 10
  }
}


模糊查询

GET test/_search
{
  "query": {
    "match": {
      "doc":{
        "query": "elastix",
        "fuzziness": "AUTO"
      }
    }
  }
}


优化查询

POST _scripts/blog_template_v1
{
  "script": {
    "lang": "mustache",
    "source": {
      "size": "{{size}}",
      "query": {
        "bool": {
          "should": [
            {
              "prefix": {
                "{{field}}.keyword": {
                  "value": "{{query}}",
                  "boost": 10
                }
              }
            },
            {
              "match_phrase_prefix": {
                "{{field}}": {
                  "query": "{{query}}",
                  "boost": 2
                }
              }
            },
            {
              "match": {
                "{{field}}": "{{query}}"
              }
            }
          ]
        }
      },
      "_source": [
        "title",
        "id",
        "uid",
        "views"
      ]
    }
  }
}


重建索引

# 新建索引
PUT blog_v1
# 查看原索引的mapping
GET blog/_mapping
# 设置索引的mapping
POST blog_v1/doc/_mapping
{
  "doc": {
    "properties": {
      "@timestamp": {
        "type": "date"
      },
      "@version": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "author": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "content": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "create_time": {
        "type": "date"
      },
      "id": {
        "type": "long"
      },
      "title": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "update_time": {
        "type": "date"
      }
    }
  }
}
# 索引迁移
POST _reindex
{
  "source": {"index": "blog"},
  "dest": {"index": "blog_v1"}
}
# 查询测试
POST /blog_v1/_search


索引别名

# 查看别名
GET _cat/aliases
# 添加别名
POST /_aliases
{
  "actions": [
    {
      "add": {
        "index": "blog",
        "alias": "my-blog"
      }
    }
  ]
}
# 切换别名
POST /_aliases
{
  "actions": [
    {
      "add": {
        "index": "blog_v1",
        "alias": "my-blog"
      }
    },
    {
      "remove": {
        "index": "blog",
        "alias": "my-blog"
      }
    }
  ]
}
#  通过别名搜索
POST my-blog/_search


拼音处理的插件

https://github.com/medcl/elasticsearch-analysis-pinyin/releases/tag/v6.3.2

添加拼音搜索字段

# 关闭索引
POST my-blog/_close
# 设置索引支持拼音分析器
PUT my-blog/_settings
{
  "index": {
    "analysis": {
      "analyzer": {
        "pinyin_analyzer": {
          "tokenizer": "my_pinyin"
        }
      },
      "tokenizer": {
        "my_pinyin": {
          "type": "pinyin",
          "keep_first_letter": true,
          "keep_separate_first_letter": true,
          "keep_full_pinyin": true,
          "keep_original": false,
          "limit_first_letter_length": 16,
          "lowercase": true
        }
      }
    }
  }
}
# 打开索引
POST my-blog/_open
# 获取原索引mapping
GET my-blog/_mapping
# 添加字段
PUT my-blog/doc/_mapping
{
  "doc": {
    "properties": {
      "@timestamp": {
        "type": "date"
      },
      "@version": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "author": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          },
          "pinyin": {
            "type": "text",
            "analyzer": "pinyin_analyzer"
          }
        }
      },
      "content": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "create_time": {
        "type": "date"
      },
      "id": {
        "type": "long"
      },
      "title": {
        "type": "text",
        "fields": {
          "keyword": {
            "type": "keyword",
            "ignore_above": 256
          }
        }
      },
      "update_time": {
        "type": "date"
      }
    }
  }
}
# 更新索引
POST my-blog/_update_by_query?conflicts=proceed
# 测试拼音搜索
POST my-blog/_search
{
  "query": {"match": {
    "author.pinyin": "libai"
  }}
}


前端显示

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <!-- 引入样式 -->
    <link
      rel="stylesheet"
      href="https://unpkg.com/element-ui/lib/theme-chalk/index.css"
    />
    <!-- 引入组件库 -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <!-- axios -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
    <style>
      /* 居中显示 */
      #app {
        width: 200px;
        margin: 0 auto;
        margin-top: 300px;
      }
      /* 搜索结果高亮 */
      em {
        color: red;
      }
    </style>
  </head>
  <body>
    <div id="app">
      <el-autocomplete
        v-model="state"
        :fetch-suggestions="querySearchAsync"
        placeholder="请输入内容"
        @select="handleSelect"
      >
        <!-- 自定义显示 -->
        <template slot-scope="{ item }">
          <div v-html="item.highlight.author[0]"></div>
        </template>
      </el-autocomplete>
    </div>
    <script>
      new Vue({
        el: "#app",
        data() {
          return {
            list: [],
            state: "",
          };
        },
        methods: {
          async querySearchAsync(queryString, cb) {
            // 查询地址
            const QUERY_URL = "http://localhost:9200/blog/_search";
            // 查询语句
            let query = {
              query: {
                match: {
                  author: queryString,
                },
              },
              highlight: {
                fields: { author: {} },
              },
            };
            const res = await axios.post(QUERY_URL, query);
            console.log(res.data.hits.hits);
            cb(res.data.hits.hits);
          },
          handleSelect(item) {
            console.log(item);
          },
        },
      });
    </script>
  </body>
</html>


image.png

相关实践学习
以电商场景为例搭建AI语义搜索应用
本实验旨在通过阿里云Elasticsearch结合阿里云搜索开发工作台AI模型服务,构建一个高效、精准的语义搜索系统,模拟电商场景,深入理解AI搜索技术原理并掌握其实现过程。
ElasticSearch 最新快速入门教程
本课程由千锋教育提供。全文搜索的需求非常大。而开源的解决办法Elasricsearch(Elastic)就是一个非常好的工具。目前是全文搜索引擎的首选。本系列教程由浅入深讲解了在CentOS7系统下如何搭建ElasticSearch,如何使用Kibana实现各种方式的搜索并详细分析了搜索的原理,最后讲解了在Java应用中如何集成ElasticSearch并实现搜索。 &nbsp;
相关文章
|
8月前
|
前端开发 API 开发工具
一年撸完百万行代码,企业微信的全新鸿蒙NEXT客户端架构演进之路
本文将要分享的是企业微信的鸿蒙Next客户端架构的演进过程,面对代码移植和API不稳定的挑战,提出了DataList框架解决方案。通过结构化、动态和认知三重熵减机制,将业务逻辑与UI解耦,实现数据驱动开发。采用MVDM分层架构(业务实体层、逻辑层、UI数据层、表示层),屏蔽系统差异,确保业务代码稳定。
368 0
|
10月前
|
弹性计算 运维 网络安全
阿里云轻量应用服务器产品解析与搭建个人博客网站教程参考
轻量应用服务器(Simple Application Server)作为阿里云面向单机应用场景推出的云服务器产品,以其一键部署、一站式管理、高性价比等特性,深受个人开发者、中小企业及入门级用户的喜爱。本文将全面解析阿里云轻量应用服务器的产品优势、应用场景、使用须知,以及使用轻量应用服务器搭建个人博客网站的详细教程,帮助用户更好地了解和使用这一产品。
|
人工智能 自然语言处理 机器人
手把手带你搭建一个语音对话机器人,5分钟定制个人AI小助手(新手入门篇)
本文介绍了如何从零开始搭建一个语音对话机器人,涵盖自动语音识别(ASR)、自然语言处理(NLP)和文本到语音合成(TTS)三大核心模块。通过使用开源工具如FunASR、LLaMA3-8B和ChatTTS,以及FastAPI和Gradio等技术,详细指导读者轻松实现个人AI小助手的构建,适合技术新手快速上手。
4996 1
|
机器学习/深度学习 监控 自动驾驶
如何使用 Python 和 OpenCV 进行实时目标检测
如何使用 Python 和 OpenCV 进行实时目标检测
|
Java
Java名称由来
2000年度的JavaOne国际会议大厅热闹非凡,一阵阵浓郁的咖啡味儿香气扑鼻。从世界各地汇集到旧金山参加会议的Java精英们兴奋异常,排着长队,等待得到一杯由Java语言控制的咖啡机煮制的免费咖啡。
1331 0
|
Java 数据库连接 Maven
|
机器学习/深度学习 传感器 算法
基于matlab模拟CA-CFAR 高频雷达目标检测单元平均恒虚警方法
基于matlab模拟CA-CFAR 高频雷达目标检测单元平均恒虚警方法
|
前端开发 API 索引
ELASTIC 搜索开发实战-笔记
ELASTIC 搜索开发实战-笔记
279 0
ELASTIC 搜索开发实战-笔记
|
数据可视化 Shell Linux
[Android电量] 耗电信息统计服务battery / BatteryStats
通过执⾏battery命令(不需要root) adb命令获取电量量消耗信息 获取整个设备的电量量消耗信息 获取某个apk的电量量消耗信息 batterystats使用步骤 通过执⾏battery命令(不需要root) 通过 adb shell dumpsys battery,返回结果后有电池的...
6862 0

热门文章

最新文章