thinkphp中使用Elasticsearch 7.0进行多表的搜索

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档

文章目录


前言

提示:thinkphp中使用Elasticsearch 7.0进行多表的搜索:

thinkphp数据库配置文件

php 复制代码
 // Elasticsearch数据库配置信息
        'elasticsearch' => [
            'scheme' =>'http',
            'host' => '127.0.0.1',
            'port' => '9200',
            'user' => '',
            'pass' => '',
            'timeout' => 2,
        ],

提示:以下是本篇文章正文内容,下面案例可供参考

一、thinkphp中使用Elasticsearch 7.0进行多表的搜索

示例:thinkphp中使用Elasticsearch 7.0进行多表的搜索

二、使用步骤

1.引入库

直接上代码如下(示例):

shell 复制代码
composer require "elasticsearch/elasticsearch": "7.0.*"

2.读入数据

代码如下(示例):

php 复制代码
namespace app\common\model;
use think\facade\Db;
use think\Model;
use Elasticsearch\ClientBuilder;
class Article extends Model
{
    protected $client;

    public function __construct($data = [])
    {
        parent::__construct($data);

        try {	
            $this->client = ClientBuilder::create()
                ->setHosts([config('database.connections.elasticsearch.host') . ':' . config('database.connections.elasticsearch.port')])
                ->build();
        } catch (\Exception $e) {
            // 输出连接错误信息
            echo $e->getMessage();
            exit;
        }
    }

    // 添加文档到Elasticsearch
    public function addDocument()
    {
        $articles = Db::name('article')->select();
        foreach ($articles as $article) {
            $data = [
                'id' => $article['id'], // 文章表的 ID
                'title' => $article['title'],
                'content' => $article['content'],
                'category_id' => $article['category_id'], // 文章表的 ID
            ];

            $params = [
                'index' => 'articles', // 索引名称
                'id' => $data['id'], // 文章 ID 作为文档的唯一标识
                'body' => $data,
            ];

            $response = $this->client->index($params);
        }
        return $response;
    }

    // 搜索文档
    public function searchDocuments($index,$query)
    {
        $params = [
            'index' => $index,
            'body' => [
                'query' => [
                    'multi_match' => [
                        'query' => $query,
                        'fields' => ['title', 'content'],
                    ],
                ],
            ],
        ];

        $response = $this->client->search($params);
        return $response;
    }
}
php 复制代码
<?php
/**
 * Created by PhpStorm.
 * User: wangkxin@foxmail.com
 * Date: 2023/9/2
 * Time: 17:55
 */

namespace app\common\model;
use think\facade\Db;
use think\Model;
use Elasticsearch\ClientBuilder;

class Book extends Model
{
    protected $client;

    public function __construct($data = [])
    {
        parent::__construct($data);

        try {
            // $host = config('database.connections.elasticsearch.host');
            // $port = config('database.connections.elasticsearch.port');
            $this->client = ClientBuilder::create()
                ->setHosts([config('database.connections.elasticsearch.host') . ':' . config('database.connections.elasticsearch.port')])
                ->build();
        } catch (\Exception $e) {
            // 输出连接错误信息
            echo $e->getMessage();
            exit;
        }
    }

    // 添加文档到Elasticsearch
    public function addDocument()
    {
        $books = Db::name('book')->select();
        foreach ($books as $book) {
            $data = [
                'id' => $book['id'], // 书籍表的 ID
                'user_id' => $book['user_id'], // 书籍表作者ID
                'book' => $book['book'],
            ];

            $params = [
                'index' => 'books', // 索引名称
                'id' => $data['id'], // 文章 ID 作为文档的唯一标识
                'body' => $data,
            ];

            $response = $this->client->index($params);
        }
        return $response;
    }

    // 搜索文档
    public function searchDocuments($index,$query)
    {
        $params = [
            'index' => $index,
            'body' => [
                'query' => [
                    'multi_match' => [
                        'query' => $query,
                        'fields' => ['book'],
                    ],
                ],
            ],
        ];

        $response = $this->client->search($params);
        return $response;
    }
}
php 复制代码
<?php
/**
 * Created by PhpStorm.
 * User: wangkxin@foxmail.com
 * Date: 2023/9/2
 * Time: 15:27
 * 全局搜素模型
 */

namespace app\common\model;

use think\Model;
use Elasticsearch\ClientBuilder;

class ElasticsearchModel extends Model
{
    protected $client;

    public function __construct($data = [])
    {
        parent::__construct($data);

        try {
            $this->client = ClientBuilder::create()
                ->setHosts([config('database.connections.elasticsearch.host') . ':' . config('database.connections.elasticsearch.port')])
                ->build();
        } catch (\Exception $e) {
            // 输出连接错误信息
            echo $e->getMessage();
            exit;
        }
    }

    public function globalSearch($keyword)
    {
        // 搜索articles索引
        $articles = $this->searchIndex('articles', $keyword);

        // 搜索books索引
        $books = $this->searchIndex('books', $keyword);

        // 合并搜索结果
        $result = array_merge($articles, $books);

        return $result;
    }

    protected function searchIndex($index, $keyword)
    {
        $params = [
            'index' => $index,
            'body' => [
                'query' => [
                    'multi_match' => [
                        'query' => $keyword,
                        'fields' => ['title', 'content','book'],
                    ],
                ],
            ],
        ];

        // 执行搜索请求
        $response = $this->client->search($params);

        // 解析结果
        $result = [];
        if (isset($response['hits']['hits'])) {
            foreach ($response['hits']['hits'] as $hit) {
                $result[] = $hit['_source'];
                $result['index'] = $index;
            }
        }

        return $result;
    }


}
php 复制代码
<?php
/**
 * Created by PhpStorm.
 * User: wangkxin@foxmail.com
 * Date: 2023/9/2
 * Time: 18:53
 */

namespace app\index\controller;

use app\common\model\ElasticsearchModel;

class SearchController
{
	//全局搜索个表间的数据
    public function search($keyword)
    {
        $searchModel = new ElasticsearchModel();
        $result = $searchModel->globalSearch($keyword);
        return json($result);
    }
}
php 复制代码
namespace app\index\controller;
use app\BaseController;
use app\common\model\Article as ElasticArticle;
use app\common\model\Book as ElasticBook;
use app\Request;
use Elasticsearch\ClientBuilder;


class Demo1 extends BaseController
{
//新增索引,建议在模型中新增 ,删除, 修改 或者使用观察者模式更新ES索引
 public function addDocument()
    {
        $elasticsearchArticle = new ElasticArticle();
        $response = $elasticsearchArticle->addDocument();
        $elasticsearchBook = new ElasticBook();
        $response1 = $elasticsearchBook->addDocument();
        return json($response);
        // print_r(json($response));
        // print_r(json($response1));
    }


 /**
     * 单独搜索文章表例子
     */
    public function search(Request $request)
    {
        $keyword = $request->param('keyword');
        $elasticsearchModel = new ElasticArticle();
        $index = 'articles';
        $query = '你';

        $response = $elasticsearchModel->searchDocuments($index, $query);
        return json($response);
    }

	//单独搜搜书籍表
    public function searchBook(Request $request)
    {
        $keyword = $request->param('keyword');
        $elasticsearchModel = new ElasticBook();
        $index = 'books';
        $query = '巴黎';

        $response = $elasticsearchModel->searchDocuments($index, $query);
        return json($response);
    }




    public function deleteIndex()
    {
        $client = ClientBuilder::create()->build();

        $params = [
            'index' => 'my_index', // 索引名称
        ];

        $response = $client->indices()->delete($params);

        if ($response['acknowledged']) {
            return '索引删除成功';
        } else {
            return '索引删除失败';
        }
    }

}

使用的表

sql 复制代码
CREATE TABLE `article` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `category_id` int(11) DEFAULT NULL,
  `title` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  `content` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=107 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


CREATE TABLE `book` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user_id` int(11) DEFAULT NULL,
  `book` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=21 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


CREATE TABLE `elasticsearch_model` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `model_name` varchar(255) NOT NULL DEFAULT '' COMMENT '模型名称',
  `index_name` varchar(255) NOT NULL DEFAULT '' COMMENT '索引名称',
  `created_time` int(11) NOT NULL DEFAULT '0' COMMENT '创建时间',
  `updated_time` int(11) NOT NULL DEFAULT '0' COMMENT '更新时间',
  PRIMARY KEY (`id`),
  UNIQUE KEY `index_name_unique` (`index_name`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COMMENT='Elasticsearch 模型配置表';

结果


windwos 上记住 安装 Elasticsearch 7.0 库, 和 kibana-7.0.0-windows-x86_64 图像管理工具

总结

提示:这是简单例子, 注意'fields' => ['title', 'content'], 尝试使用搜索number型字段,索引报错, 貌似只支持txt类型字段搜索

例如:以上就是今天要讲的内容,本文仅仅简单介绍了Elasticsearch的使用

相关推荐
狼头长啸李树身1 小时前
眼儿媚·秋雨绵绵窗暗暗
大数据·网络·服务发现·媒体
Json_181790144802 小时前
商品详情接口使用方法和对接流程如下
大数据·json
Data 3172 小时前
Hive数仓操作(十七)
大数据·数据库·数据仓库·hive·hadoop
bubble小拾6 小时前
ElasticSearch高级功能详解与读写性能调优
大数据·elasticsearch·搜索引擎
ZOHO项目管理软件6 小时前
EDM平台大比拼 用户体验与营销效果双重测评
大数据
不能放弃治疗7 小时前
重生之我们在ES顶端相遇第 18 章 - Script 使用(进阶)
elasticsearch
HyperAI超神经7 小时前
Meta 首个多模态大模型一键启动!首个多针刺绣数据集上线,含超 30k 张图片
大数据·人工智能·深度学习·机器学习·语言模型·大模型·数据集
hengzhepa7 小时前
ElasticSearch备考 -- Search across cluster
学习·elasticsearch·搜索引擎·全文检索·es
Hello.Reader9 小时前
TopK算法在大数据重复数据分析中的应用与挑战
大数据·算法·数据分析
数据龙傲天9 小时前
1688商品API接口:电商数据自动化的新引擎
java·大数据·sql·mysql