【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 [];
}
相关推荐
Leo1876 小时前
MySQL 回表(Back to Table)详解
数据库·mysql
遇见火星6 小时前
MySQL 8.0复制架构主从自动切换脚本
mysql·adb·架构·mysql8.0·mysql主从
不知江月待何人..6 小时前
MySQL服务无法启动问题
数据库·mysql
李少兄7 小时前
一文搞懂什么是关系型数据库?什么是非关系型数据库?
数据库·redis·mysql·mongodb·nosql
sysinside7 小时前
Elasticsearch 9.2 发布 - 分布式搜索和分析引擎
大数据·分布式·elasticsearch
会开花的二叉树7 小时前
即时通讯系统核心模块实现
数据库·mysql·elasticsearch
Jinkxs7 小时前
Elasticsearch - 倒排索引的压缩算法 Elasticsearch 如何节省空间
大数据·elasticsearch·搜索引擎
地瓜伯伯7 小时前
SpringBoot项目整合Elasticsearch启动失败的常见错误总结(2)
spring boot·elasticsearch·spring cloud
阿里云大数据AI技术8 小时前
真实案例复盘:从“三套烟囱”到 All in ES,这家企业如何砍掉 40%运维成本?
人工智能·elasticsearch·搜索引擎
四谎真好看9 小时前
MySQL 学习笔记(运维篇1)
运维·数据库·笔记·学习·mysql·学习笔记