Elasticsearch 简单搜索查询案例

1.MySql表结构/数据

SET FOREIGN_KEY_CHECKS=0;-- ----------------------------
-- Table structure for user_lables
-- ----------------------------
DROP TABLE IF EXISTS `user_lables`;
CREATE TABLE `user_lables` (`id` varchar(255) DEFAULT NULL COMMENT '用户唯一标识',`age` varchar(255) DEFAULT NULL COMMENT '用户年龄',`sex` varchar(255) DEFAULT NULL COMMENT '用户性别 1:男,2:女',`tel` varchar(255) DEFAULT NULL COMMENT '联系电话',`is_high` varchar(255) DEFAULT NULL COMMENT '高价值用户 0:否,1:是',`final_by` varchar(255) DEFAULT NULL COMMENT '最后下单时间'
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb3;-- ----------------------------
-- Records of user_lables
-- ----------------------------
INSERT INTO `user_lables` VALUES ('10001', '23', '1', '130xxxx1111', '1', '2022-09-11 22:10:12');
INSERT INTO `user_lables` VALUES ('10002', '33', '1', '157xxxx4506', '0', '2023-06-13 12:09:11');
INSERT INTO `user_lables` VALUES ('10003', '24', '2', '157xxxx4309', '1', '2023-07-15 22:19:21');
INSERT INTO `user_lables` VALUES ('10004', '16', '1', '151xxxx5516', '1', '2023-06-29 12:29:31');
INSERT INTO `user_lables` VALUES ('10005', '18', '1', '152xxxx4506', '1', '2023-07-17 17:39:41');
INSERT INTO `user_lables` VALUES ('10006', '19', '2', '153xxxx4506', '0', '2023-07-18 19:49:51');
INSERT INTO `user_lables` VALUES ('10007', '20', '2', '157xxxx4506', '1', '2023-07-18 23:59:11');
INSERT INTO `user_lables` VALUES ('10008', '23', '1', '189xxxx4506', '0', '2023-06-14 16:39:51');
INSERT INTO `user_lables` VALUES ('10009', '36', '2', '137xxxx4506', '1', '2023-06-15 13:29:41');
INSERT INTO `user_lables` VALUES ('10010', '45', '2', '130xxxx4506', '1', '2023-06-29 09:19:31');
INSERT INTO `user_lables` VALUES ('10011', '30', '1', '157xxxx4506', '1', '2023-07-14 21:09:21');
INSERT INTO `user_lables` VALUES ('10012', '33', '2', '157xxxx4506', '0', '2023-07-13 22:29:11');
INSERT INTO `user_lables` VALUES ('10013', '29', '2', '157xxxx4516', '0', '2023-07-13 23:23:21');
INSERT INTO `user_lables` VALUES ('10014', '28', '1', '157xxxx5516', '0', '2023-07-13 23:22:21');

2.Java 实体类

2.1 user_lables表实体

public class User_lables {private String id;private String age;private String sex;private String tel;private String is_high;private String final_by;public String getId() {return id;}public void setId(String id) {this.id = id;}public String getAge() {return age;}public void setAge(String age) {this.age = age;}public String getSex() {return sex;}public void setSex(String sex) {this.sex = sex;}public String getTel() {return tel;}public void setTel(String tel) {this.tel = tel;}public String getIs_high() {return is_high;}public void setIs_high(String is_high) {this.is_high = is_high;}public String getFinal_by() {return final_by;}public void setFinal_by(String final_by) {this.final_by = final_by;}public User_lables(String id, String age, String sex, String tel, String is_high, String final_by) {this.id = id;this.age = age;this.sex = sex;this.tel = tel;this.is_high = is_high;this.final_by = final_by;}public User_lables() {}@Overridepublic String toString() {return "User_lables{" +"id='" + id + '\'' +", age='" + age + '\'' +", sex='" + sex + '\'' +", tel='" + tel + '\'' +", is_high='" + is_high + '\'' +", final_by='" + final_by + '\'' +'}';}

2.2 查询参数实体

public class Es_bean {private String name;private String type;private String value;public String getName() {return name;}public void setName(String name) {this.name = name;}public String getType() {return type;}public void setType(String type) {this.type = type;}public String getValue() {return value;}public void setValue(String value) {this.value = value;}
}

3.整体代码

package com.jinshan.datacenter.estest;/*** @author MR.Liu* @version 1.0* @data 2023-07-20 11:19*/
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.jinshan.datacenter.es.Es_bean;
import com.jinshan.datacenter.es.User_lables;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.http.HttpHost;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;public class MySQLDemo {// MySQL 8.0 以下版本 - JDBC 驱动名及数据库 URLstatic final String JDBC_DRIVER = "com.mysql.jdbc.Driver";static final String DB_URL = "jdbc:mysql://localhost:3306/test";// MySQL 8.0 以上版本 - JDBC 驱动名及数据库 URL//static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";//static final String DB_URL = "jdbc:mysql://localhost:3306/RUNOOB?useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";// 数据库的用户名与密码,需要根据自己的设置static final String USER = "root";static final String PASS = "000000";public static Connection GetConn(){Connection conn = null;try{// 注册 JDBC 驱动Class.forName(JDBC_DRIVER);// 打开链接System.out.println("连接数据库...");conn = DriverManager.getConnection(DB_URL,USER,PASS);// 执行查询System.out.println(" 实例化Statement对象...");}catch(SQLException se){// 处理 JDBC 错误se.printStackTrace();} catch (ClassNotFoundException e) {throw new RuntimeException(e);}return conn;}public static void InsertDoc(RestHighLevelClient client, String indexName , List<User_lables> list) throws IOException {// 批量导入数据BulkRequest request = new BulkRequest();// 添加索引请求到批量请求中for (int i =0;i<list.size();i++){Gson gson = new Gson();String json = gson.toJson(list.get(i));request.add(new IndexRequest(indexName).id(String.valueOf(i)).source(json, XContentType.JSON));}// 发送批量请求try {BulkResponse response = client.bulk(request, RequestOptions.DEFAULT);if (response.hasFailures()) {System.out.println("批量导入数据失败:" + response.buildFailureMessage());} else {System.out.println("批量导入数据成功");}} catch (IOException e) {e.printStackTrace();}}public static void main(String[] args) throws SQLException, IOException {// 创建客户端对象RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(new HttpHost("localhost", 9200, "http")));Connection conn = GetConn();Statement stat=conn.createStatement();String sql = "select * from user_lables";ResultSet rs = stat.executeQuery(sql);BeanListHandler<User_lables> bh =new BeanListHandler<User_lables>(User_lables.class);//rs是ResultSet得到的从返回集合List<User_lables> handle = bh.handle(rs);//InsertDoc(client,"user_test1",handle);String data = "{\n" +"  \"selectedTags\": [\n" +"    {\n" +"      \"effect\": \"user\",\n" +"      \"label\": \"男性\",\n" +"      \"name\": \"sex\",\n" +"      \"value\": \"1\",\n" +"      \"type\": \"match\"\n" +"    },\n" +"    {\n" +"      \"effect\": \"user\",\n" +"      \"label\": \"10~50\",\n" +"      \"name\": \"age\",\n" +"      \"value\": \"20-30\",\n" +"      \"type\": \"rangeBoth\"\n" +"    },\n" +"    {\n" +"      \"effect\": \"user\",\n" +"      \"label\": \"高质量用户\",\n" +"      \"name\": \"is_high\",\n" +"      \"value\": \"0\",\n" +"      \"type\": \"match\"\n" +"    }\n" +"  ]\n" +"}";JSONObject object = JSON.parseObject(data);JSONArray array = object.getJSONArray("selectedTags");List<Es_bean> list = array.toJavaList(Es_bean.class);SearchRequest request = new SearchRequest();request.indices("user_test1");request.types("_doc");SearchSourceBuilder builder = new SearchSourceBuilder();request.source(builder);String[] includes = {"id", "age","sex","tel","is_high","final_by"};builder.fetchSource(includes, null);builder.from(0);builder.size(1000);BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();for (int i=0;i<list.size();i++) {String name = list.get(i).getName();String value = list.get(i).getValue();String type = list.get(i).getType();if (type.equals("match")) {boolQueryBuilder.must(QueryBuilders.matchQuery(name, value));}if (type.equals("rangeBoth")) {String[] split = value.split("-");String v1 = split[0];String v2 = split[1];boolQueryBuilder.must(QueryBuilders.rangeQuery(name).lte(v2).gte(v1));}}builder.query(boolQueryBuilder);request.source(builder);RequestOptions options = RequestOptions.DEFAULT;List<User_lables> memberTags = new ArrayList<>();try {SearchResponse search = client.search(request, options);SearchHits hits = search.getHits();Iterator<SearchHit> iterator = hits.iterator();while (iterator.hasNext()) {SearchHit hit = iterator.next();String sourceAsString = hit.getSourceAsString();User_lables memberTag = JSON.parseObject(sourceAsString, User_lables.class);System.out.println(memberTag);memberTags.add(memberTag);}} catch (IOException e) {e.printStackTrace();}conn.close();client.close();}
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/8196.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

CNN(卷积神经网络)的实现过程详解

概要 在图像处理领域&#xff0c;CNN(卷积神经网络)处于绝对统治地位&#xff0c;但对于CNN具体是如何用神经网络实现的&#xff0c;能找到的介绍要么是一大堆数学公式&#xff0c;要么是大段晦涩的文字说明&#xff0c;读起来很是辛苦&#xff0c;想写好一片完整的而且有深度的…

【开源项目】低代码数据可视化开发平台-Datav

Datav 基本介绍 Datav是一个Vue3搭建的低代码数据可视化开发平台&#xff0c;将图表或页面元素封装为基础组件&#xff0c;无需编写代码即可完成业务需求。 它的技术栈为&#xff1a;Vue3 TypeScript4 Vite2 ECharts5 Axios Pinia2 在线预览 账号: admin 密码: 123123预…

Spring Cloud+Spring Boot+Mybatis+uniapp+前后端分离实现知识付费平台免费搭建

Java版知识付费-轻松拥有知识付费平台 多种直播形式&#xff0c;全面满足直播场景需求 公开课、小班课、独立直播间等类型&#xff0c;满足讲师个性化直播场景需求&#xff1b;低延迟、双向视频&#xff0c;亲密互动&#xff0c;无论是互动、答疑&#xff0c;还是打赏、带货、…

Redis底层封装细节

日常我们程序员在使用redis做缓存的时候&#xff0c;很少会直接使用到RedisTemplate直接操作k-v键值对&#xff0c;而是通过对RedisTemplate原生代码的封装&#xff0c;来构建我们日常便于使用习惯的代码来操作数据&#xff0c;这里我分享一下日常基本的对RedisTemplate底层的封…

[nlp] tokenizer加速:fast_tokenizer=True

fast_tokenizer 是一个布尔值参数,用于指定是否使用快速的 tokenizer。在某些情况下,使用快速的 tokenizer 可以加快模型训练和推理速度。如果 fast_tokenizer 参数为 True,则会使用快速的 tokenizer;否则,将使用默认的 tokenizer。 快速的 tokenizer 通常使用一些技巧来减…

使用Newtonsoft直接读取Json格式文本(Linq to Json)

使用Newtonsoft直接读取Json格式文本&#xff08;Linq to Json&#xff09; 使用 Newtonsoft.Json&#xff08;通常简称为 Newtonsoft&#xff09;可以轻松地处理 JSON 格式的文本。Newtonsoft.Json 是 .NET 中一个流行的 JSON 处理库&#xff0c;它提供了丰富的功能和灵活性。…

微信小程序实现蓝牙开锁、开门、开关、指令发送成功,但蓝牙设备毫无反应、坑

文章目录 开源htmlJavaScript 开源 wx联系本人获取源码(开源): MJ682517 html <view><view class"p_l_36 p_r_36"><input class"w_100_ h_80 lh_80 ta_c b_2s_eee radius_20" value"{{instructVal}}" type"text" plac…

RocketMq 事务消息原理

Rocketmq 事务消息API使用 使用TransactionMQProducer类。 实现TransactionListener 接口覆盖其方法executeLocalTransaction和checkLocalTransaction 即可。 其中executeLocalTransaction 执行本地方法和checkLocalTransaction 事务状态回查。 玩法 简历一张本地事务表&…

51单片机定时器

51单片机定时器 1.简介 C51中的定时器和计数器是同一个硬件电路支持的&#xff0c;通过寄存器配置不同&#xff0c;就可以将他当做定时器 或者计数器使用。 确切的说&#xff0c;定时器和计数器区别是致使他们背后的计数存储器加1的信号不同。当配置为定时器使 用时&#xff0…

回归预测 | MATLAB实现TCN-BiGRU时间卷积双向门控循环单元多输入单输出回归预测

回归预测 | MATLAB实现TCN-BiGRU时间卷积双向门控循环单元多输入单输出回归预测 目录 回归预测 | MATLAB实现TCN-BiGRU时间卷积双向门控循环单元多输入单输出回归预测预测效果基本介绍模型描述程序设计参考资料 预测效果 ![6 基本介绍 1.MATLAB实现TCN-BiGRU时间卷积双向门控循…

JSON格式Python,Java,PHP等封装获取淘宝商品详情描述数据API

淘宝是一个网上购物平台&#xff0c;售卖各类商品&#xff0c;包括服装、鞋类、家居用品、美妆产品、电子产品等。要获取淘宝天猫商品详情描述数据&#xff0c;您可以通过开放平台的接口或者直接访问淘宝天猫商城的网页来获取商品详情详细信息。以下是两种常用方法的介绍&#…

C语言假期作业 DAY 02

题目 一、选择题 1、以下程序段的输出结果是&#xff08; &#xff09; #include<stdio.h> int main() {char s[] "\\123456\123456\t";printf("%d\n", strlen(s));return 0; } A: 12 B: 13 C: 16 D: 以上都不对 2、若有以下程序&#xff0c;则运行…

实现基于UDP简易的英汉词典

文章目录 实现目标认识相关接口socketbzerobindrecvfromsendto 实现思路和注意事项完整代码Server.hppServer.ccClient.hppClient.cc 运行效果END 实现目标 实现一个服务端和一个客户端&#xff0c;客户端负责发送一个单词&#xff0c;服务端接收到后将翻译后的结果返回发送到…

Linux下C++ STL获取Mac地址

在Ubuntu下&#xff0c;你可以使用以下代码来获取MAC地址&#xff1a; #include <iostream>using namespace std;#include <iostream> #include <fstream> #include <string>std::string getMACAddress() {std::string macAddress;std::ifstream file…

蓝桥杯2023年第十四届省赛-飞机降落

题目描述 N 架飞机准备降落到某个只有一条跑道的机场。其中第 i 架飞机在 Ti 时刻到达机场上空&#xff0c;到达时它的剩余油料还可以继续盘旋 Di 个单位时间&#xff0c;即它最早 可以于 Ti 时刻开始降落&#xff0c;最晚可以于 Ti Di 时刻开始降落。降落过程需要 Li个单位时…

Android 之 动画合集之帧动画

本节引言&#xff1a; 从本节开始我们来探究Android中的动画&#xff0c;毕竟在APP中添加上一些动画&#xff0c;会让我们的应用变得 很炫&#xff0c;比如最简单的关开Activity&#xff0c;当然自定义控件动画肯定必不可少啦~而Android中的动画 分为三大类&#xff0c;逐帧动画…

了解uuid

目录 一.认识 UUID 二.UUID 会耗尽吗 三.UUID 会重复吗 四.UUID 的版本 五.UUID的应用 六.java 如何生成UUID 一.认识 UUID uuid是经过特定的算法得到的. UUID 是 16 字节 128 位长的数字&#xff0c;通常以 36 字节的字符串表示&#xff0c;示例如下&#xff1a; 3F2…

boardmix AI:让工作效率翻倍的AI智能在线白板软件!

随着ChatGPT热度的飙升&#xff0c;AI逐步深入到各个领域&#xff0c;尤其在技术领域&#xff0c;引发了一场AI的新浪潮&#xff0c;人们谈论的焦点都与AI有关。 AI工具不仅帮助企业节约了成本&#xff0c;还极大提高了生产力。那些尚未融入AI的行业和产品&#xff0c;有着被AI…

OSI 和 TCP/IP 网络分层模型详解(基础)

OSI模型: 即开放式通信系统互联参考模型&#xff08;Open System Interconnection Reference Model&#xff09;&#xff0c;是国际标准化组织&#xff08;ISO&#xff09;提出的一个试图使各种计算机在世界范围内互连为网络的标准框架&#xff0c;简称OSI。 OSI 七层模型 OS…

Windows环境部署安装Chatglm2-6B-int4

chatglm2-6B是最近比较火爆的大模型&#xff0c;可以在消费级显卡上部署使用&#xff0c;适合学习。但是一般人也不一定有那么高的硬件配置&#xff0c;所以部署个int4版本应该是大多数人的最好选择。我就在家里部署起了int4版本的chatglm2-6B&#xff0c;记录一下免得忘了。 …