pdphilip/elasticlens 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

pdphilip/elasticlens

Composer 安装命令:

composer require pdphilip/elasticlens

包简介

Search your Laravel models with the convenience of Eloquent and the power of Elasticsearch

README 文档

README

ElasticLens for Laravel

[![Latest Version on Packagist](https://img.shields.io/packagist/v/pdphilip/elasticlens.svg?style=flat-square)](https://packagist.org/packages/pdphilip/elasticlens) [![GitHub Tests Action Status](https://img.shields.io/github/actions/workflow/status/pdphilip/elasticlens/run-tests.yml?branch=main&label=tests&style=flat-square)](https://github.com/pdphilip/elasticlens/actions?query=workflow%3Arun-tests+branch%3Amain) [![GitHub Code Style Action Status](https://img.shields.io/github/actions/workflow/status/pdphilip/elasticlens/fix-php-code-style-issues.yml?branch=main&label=code%20style&style=flat-square)](https://github.com/pdphilip/elasticlens/actions?query=workflow%3A"Fix+PHP+code+style+issues"+branch%3Amain) [![Total Downloads](http://img.shields.io/packagist/dt/pdphilip/elasticlens.svg)](https://packagist.org/packages/pdphilip/elasticlens)

Search your Laravel models with Eloquent ease and Elasticsearch power

Scout's simplicity • Elasticsearch's power • Your rules

// Add a trait. Search your models.
User::search('mass donuts');
// Phrase match + filters + embedded fields + pagination. One query.
User::viaIndex()
    ->searchPhrase('mass donuts')
    ->where('status', 'active')
    ->where('logs.country', 'Norway')
    ->orderByDesc('created_at')
    ->paginate(10);
// Find every user within 5km who mentioned "espressos" in their profile.
// Sorted by distance. Because priorities.
User::viaIndex()
    ->searchTerm('espressos')
    ->whereGeoDistance('home.location', '5km', [40.7128, -74.0060])
    ->orderByGeo('home.location', [40.7128, -74.0060])
    ->get();

Scout gives you a search box behind a black box. ElasticLens gives you a search engine you can open up.

Every index is a real Eloquent model you own. You define the field mappings. You define the schema. You see exactly what's indexed and how. No magic, no guessing, no driver abstractions between you and your data.

Powered by Laravel-Elasticsearch.

How It Works

1. Add the trait

class User extends Model
{
    use Indexable;
}

2. Generate the index model

php artisan lens:make User

Creates IndexedUser: a real Elasticsearch model that stays synced with your User via observers. Every create, update, delete is reflected automatically.

3. Search

// Quick search across all fields
User::search('vinyl collecting');

// Full Elasticsearch query builder. Go nuts.
User::viaIndex()->searchTerm('vinyl')->where('state', 'active')->get();
User::viaIndex()->searchFuzzy('elsticsearsh')->get();   // can't even spell it? no problem
User::viaIndex()->whereRegex('hobby', 'sw(im|itch)')->paginate(10);

Embed Relationships

Here's where the "oh cool" becomes "holy shit."

You've got a User model. Profiles in one table. Company in another. Logs in a third. Country in a fourth. In SQL, searching across all of that is a JOIN nightmare you pretend doesn't bother you. With ElasticLens, you flatten everything into one searchable document:

class IndexedUser extends IndexModel
{
    protected $baseModel = User::class;

    public function fieldMap(): IndexBuilder
    {
        return IndexBuilder::map(User::class, function (IndexField $field) {
            $field->text('first_name');
            $field->text('last_name');
            $field->text('email');
            $field->type('state', UserState::class);

            // Embed the user's profiles as nested objects
            $field->embedsMany('profiles', Profile::class)->embedMap(function ($field) {
                $field->text('bio');
                $field->array('tags');
            });

            // Embed the company they belong to
            $field->embedsBelongTo('company', Company::class)->embedMap(function ($field) {
                $field->text('name');
                $field->text('industry');
            });

            // Last 10 logs only. We're not animals.
            $field->embedsMany('logs', UserLog::class, null, null, function ($query) {
                $query->orderBy('created_at', 'desc')->limit(10);
            })->embedMap(function ($field) {
                $field->text('action');
                $field->text('ip');
            });
        });
    }
}

Now search across all of it:

// Active users at tech companies whose profiles mention "elasticsearch"
User::viaIndex()
    ->where('state', 'active')
    ->where('company.industry', 'Technology')
    ->where('profiles.bio', 'like', '%elasticsearch%')
    ->get();

Six SQL tables. Zero JOINs. One query.

Update a Profile? The parent IndexedUser rebuilds automatically. The observer chain traces all the way up. You don't have to think about it.

Conditional Indexing

Not everything deserves an index entry:

class User extends Model
{
    use Indexable;

    public function excludeIndex(): bool
    {
        return $this->is_banned; // bye
    }
}

Excluded records are tracked as skipped (not failed) in build state and health checks.

Index Migrations

Define your Elasticsearch mapping with a Blueprint. Same idea as database migrations:

public function migrationMap(): callable
{
    return function (Blueprint $index) {
        $index->text('first_name');
        $index->keyword('first_name');
        $index->text('email');
        $index->keyword('email');
        $index->keyword('state');
        $index->nested('profiles');
    };
}
php artisan lens:migrate User
ElasticLens Migrate

CLI Tools

php artisan lens:status              # Bird's eye view of all indexes
php artisan lens:health User         # Deep health check for one index
php artisan lens:build User          # Bulk rebuild all records
php artisan lens:migrate User        # Drop, migrate, rebuild. The nuclear option.
php artisan lens:make Profile        # Generate a new index model
ElasticLens Status

ElasticLens Build

Soft Delete Support

Configure globally or per-model whether soft-deleted records keep their index:

// config/elasticlens.php
'index_soft_deletes' => true,
// Or per index model
class IndexedUser extends IndexModel
{
    protected ?bool $indexSoftDeletes = true;
}

Restoring a model rebuilds its index automatically.

Requirements

Version
PHP8.2+
Laravel10 / 11 / 12
Elasticsearch8.x

Installation

composer require pdphilip/elasticlens
php artisan lens:install    # Publish config
php artisan migrate         # Create build state + migration log indexes

Requires a configured Laravel-Elasticsearch connection. Setup guide ->

Documentation

Full docs at elasticlens.pdphilip.com

Credits

License

The MIT License (MIT). See License File.

pdphilip/elasticlens 适用场景与选型建议

pdphilip/elasticlens 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 29.61k 次下载、GitHub Stars 达 0, 最近一次更新时间为 2024 年 08 月 21 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「elasticsearch」 「laravel」 「eloquent」 「PDPhilip」 「elasticlens」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 pdphilip/elasticlens 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 pdphilip/elasticlens 我们能提供哪些服务?
定制开发 / 二次开发

基于 pdphilip/elasticlens 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 29.61k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 4
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-08-21