【Elasticsearch】在es中实现mysql中的FIND_IN_SET查询条件

需求场景: 有个文章表里面有个type字段,它存储的是文章类型,有 1头条、2推荐、3热点、4图文等等 。

商品表中有一个type字段,储存的事商品类型例如:1.热销单品,2.品类TOP10,3.销量榜TOP10等等

它的type字段值很有可能是1,2,3,4

在mysql中实现语句

bash 复制代码
select * from product where FIND_IN_SET('4',type)

就可以查询到实例里的数据,那么在es里要怎么实现呢!?

es中实现mysql中的FIND_IN_SET查询条件

第一步:插入数据时将原有的1,2,3,4修改成数组1,2,3,4

php 复制代码
$string = '1,2,3,4,5';
//将数据库里的字符串分割成数组,将输入存入es内
$array = explode(",", $string);
$data['type'] = $array;
$params = [
    'index' => 'index_new', // 索引名称
    'type' => 'my_type',  // 类型名称(注意:在 Elasticsearch 7.x+ 中,类型已被弃用)
    'id' => $id,        // 文档ID(可选,如果不提供,则自动生成)
    'body' => $data,
];
 // 添加文档到索引
 return $this->client->index($params);

第二步:查询type内包含4的数据

php 复制代码
// 初始化查询参数数组
$params = [
    'index' => 'index_new', // 设置索引名称为'index_new'
    'body' => [ // 查询主体内容
        'query' => [ // 定义查询结构
            'bool' => [ // 使用布尔查询组合多个查询条件
                'must' => [ // 必须满足以下所有条件
                    [ // 匹配 type 字段的特定值
                        'terms' => [ // 使用terms查询匹配多个值
                            'type' => [4] // 查询条件为type字段等于4。此处[type]应为[type_id],若按原需求应匹配type_id字段,则为笔误。
                        ]
                    ],
                ]
            ]
        ]
    ]
];

$response = $this->client->search($params);
// 处理响应
if (isset($response['hits']['hits']) && !empty($response['hits']['hits'])) {
    // 遍历结果并输出
    return $response['hits']['hits'];
} else {
    return [];
}
相关推荐
Dovis(誓平步青云)4 小时前
现场问题先关闭还是先验收,建筑任务怎样处理依赖
前端·javascript·数据库·mysql·音视频
xuefuhe5 小时前
MySQL:group_replication_start_on_boot vs group_replication_bootstrap_group
mysql
for_ever_love__5 小时前
MySQL Online DDL 完全指南:INSTANT/INPLACE/COPY 三种算法、MDL 锁事故与 gh-ost 实战
数据库·mysql·ddl·online·gh-ost·锁表·加字段
for_ever_love__5 小时前
MySQL 子查询、派生表与 CTE 优化:半连接、物化和递归实战
数据库·mysql·优化·as·子查询·with·cte
鱼宵6 小时前
LangChain4j 生产化改造:记忆落 Redis、向量落 ES,重启再也不丢
数据库·redis·elasticsearch·langchain4j
小巫山云子7 小时前
Git的用法
大数据·git·elasticsearch
鱼很腾apoc7 小时前
【MySQL】 第1期 从核心概念到表约束全解析
linux·c语言·数据库·学习·mysql
Elasticsearch8 小时前
多租户集群中的 Kubernetes 吵闹邻居:使用 ES|QL 找出它
elasticsearch
斯内普吖8 小时前
(开源)校园充电宝租借管理系统实战指南 基于 Java + SSM + Vue + MySQL
java·vue.js·mysql·开源
Elasticsearch8 小时前
你的 AI 聊天不应只是一张截图:Elastic Agent Builder 中的实时共享对话
elasticsearch