opsource/queryadapter 问题修复 & 功能扩展

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

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

opsource/queryadapter

Composer 安装命令:

composer require opsource/queryadapter

包简介

Revolutionize your Laravel query management with Laravel Query Adapter! Our adapter package includes multiple query executioners, including Elasticsearch and Eloquent, to help you efficiently run your Laravel queries. Say goodbye to query management headaches and hello to seamless query execution wi

README 文档

README

Here’s an optimized version of your document:

QueryAdapter

QueryAdapter is a powerful Laravel package that provides an intuitive abstraction layer for interacting with Elasticsearch indices. It includes a set of query builders designed for searching, aggregating, and suggesting data, while offering essential utilities for efficient index management. This package enables developers to work with Elasticsearch in a structured and efficient way, eliminating the complexity of low-level queries.

Installation

To get started, install the package via Composer:

composer require opsource/query-adapter

Usage

Setting Up

Before using the QueryAdapter package, ensure that your Elasticsearch client is properly configured. The package relies on ElasticClient to manage all Elasticsearch communications, ensuring smooth data indexing and retrieval.

Interacting with Indices

The InteractsWithIndex trait offers powerful methods to manage and query Elasticsearch indices efficiently.

Bulk Insert

Insert multiple documents into an Elasticsearch index in a single operation for improved performance:

$data = [
    ['index' => ['_id' => 1]],
    ['name' => 'Product A', 'price' => 100],
    ['index' => ['_id' => 2]],
    ['name' => 'Product B', 'price' => 200],
];

$result = $this->bulk($data);

Fetch Index Information

Retrieve detailed information about a specific index, including settings and mappings:

$indexInfo = $this->catIndices('my_index');

Delete an Index

Remove an index when it is no longer needed:

$result = $this->indicesDelete('my_index');

Create a New Index with Custom Settings

Define and create a new Elasticsearch index with custom settings:

$settings = [
    'settings' => [
        'number_of_shards' => 1,
        'number_of_replicas' => 1
    ]
];

$result = $this->indicesIndex('my_new_index', $settings);

Refresh an Index

Make recent operations visible to search queries:

$result = $this->indicesRefresh();

Querying Data

QueryAdapter simplifies querying with its builder-based approach.

Search Query

Perform a basic search query:

$query = $this->query()->match('name', 'Product A')->get();

Index Class Example

Create an index class similar to an Eloquent model:

use Ensi\LaravelElasticQuery\ElasticIndex;

class ProductsIndex extends ElasticIndex
{
    protected string $name = 'test_products';
    protected string $indicator = 'product_id';
}

Set a unique document attribute name for $indicator, which is used as an additional sort in search_after.

Query Example

Perform a search with complex filters and sorting:

$searchQuery = ProductsIndex::queryEngine();

$hits = $searchQuery
             ->where('rating', '>=', 5)
             ->whereDoesntHave('offers', fn(BoolQuery $queryEngine) => $queryEngine->where('seller_id', 10)->where('active', false))
             ->sortBy('rating', 'desc')
             ->sortByNested('offers', fn(SortableQuery $queryEngine) => $queryEngine->where('active', true)->sortBy('price', mode: 'min'))
             ->take(25)
             ->get();

Filtering

$searchQuery->where('field', 'value');
$searchQuery->where('field', '>', 'value'); // Operators: `=`, `!=`, `>`, `<`, `>=`, `<=`
$searchQuery->whereNot('field', 'value'); // Equivalent to `where('field', '!=', 'value')`
$searchQuery->whereIn('field', ['value1', 'value2']);
$searchQuery->whereNotIn('field', ['value1', 'value2']);
$searchQuery->whereNull('field');
$searchQuery->whereNotNull('field');

Nested Queries

$searchQuery->whereHas('nested_field', fn(BoolQuery $subQuery) => $subQuery->where('field_in_nested', 'value'));
$searchQuery->whereDoesntHave('nested_field', function (BoolQuery $subQuery) {
    $subQuery->whereHas('nested_field', fn(BoolQuery $subQuery2) => $subQuery2->whereNot('field', 'value'));
});

nested_field must have nested type. Subqueries can only use subdocument fields.

Full-Text Search

$searchQuery->whereMatch('field_one', 'queryEngine string');
$searchQuery->whereMultiMatch(['field_one^3', 'field_two'], 'queryEngine string', MatchType::MOST_FIELDS);

Sorting

$searchQuery->sortBy('field', SortOrder::DESC, SortMode::MAX, MissingValuesMode::FIRST);
$searchQuery->sortByNested('nested_field', fn(SortableQuery $subQuery) => $subQuery->where('field_in_nested', 'value')->sortBy('field'));

Use dedicated sort methods for each sort type:

$searchQuery->minSortBy('field', 'asc');
$searchQuery->maxSortBy('field', 'asc');
$searchQuery->avgSortBy('field', 'asc');
$searchQuery->sumSortBy('field', 'asc');
$searchQuery->medianSortBy('field', 'asc');

Pagination

Offset Pagination

$page = $searchQuery->paginate(15, 45);

Cursor Pagination

$page = $searchQuery->cursorPaginate(10);
$pageNext = $searchQuery->cursorPaginate(10, $page->next);

Aggregation

Create aggregation queries:

$aggQuery = ProductsIndex::aggregate();

$aggs = $aggQuery
            ->where('active', true)
            ->terms('codes', 'code')
            ->count('product_count', 'product_id')
            ->nested(
                'offers',
                fn(AggregationsBuilder $builder) => $builder->where('seller_id', 10)->minmax('price', 'price')
            );

Aggregate Types

$aggQuery->terms('agg_name', 'field', 25);
$aggQuery->minmax('agg_name', 'field');
$aggQuery->count('agg_name', 'field');

Suggesting

Create suggest queries for autocomplete or typo correction:

$sugQuery = ProductsIndex::suggest();
$suggests = $sugQuery->phrase('suggestName', 'name.trigram')->text('glves')->size(1)->shardSize(3)->get();

Suggester Types

Term Suggester:

$aggQuery->term('suggestName', 'name.trigram')->text('glves')->get();

Phrase Suggester:

$aggQuery->phrase('suggestName', 'name.trigram')->text('glves')->get();

CLI Commands

engine:make

Generates various engine components:

php artisan engine:make {type} [--model=] [--module=] [--index=] [--force] [--facade] [--job]

engine:make-facade

Generates a facade for a search engine model.

engine:make-directive

Creates a directive class for a search engine model.

Query Log

Enable query logging to track executed queries:

ElasticQuery::enableQueryLog();
$records = ElasticQuery::getQueryLog();
ElasticQuery::disableQueryLog();

Environment Variables

Configure the following environment variables:

ELASTICSEARCH_HOSTS=https://localhost:9200
ELASTICSEARCH_RETRIES=2
ELASTICSEARCH_USERNAME=admin
ELASTICSEARCH_PASSWORD=admin
ELASTICSEARCH_SSL_VERIFICATION=true

Elasticsearch Version Compatibility

Separate releases are created for Elasticsearch 7 and 8. Development for each version occurs in corresponding branches.

Contributing

See CONTRIBUTING for details.

License

MIT License. See LICENSE.md for more information.

This version improves readability and structure while maintaining clarity. It consolidates sections, removes redundancy, and ensures consistency throughout the document.

opsource/queryadapter 适用场景与选型建议

opsource/queryadapter 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 506 次下载、GitHub Stars 达 6, 最近一次更新时间为 2024 年 12 月 01 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

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

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 506
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 6
  • 点击次数: 14
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 6
  • Watchers: 1
  • Forks: 1
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2024-12-01