PHPackages                             rapiddive/nrql-builder - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. rapiddive/nrql-builder

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

rapiddive/nrql-builder
======================

Query builder for New Relic Query Language (NRQL)

2.0.1(2w ago)021Apache-2.0PHPPHP &gt;=8.0CI passing

Since Aug 28Pushed 2w ago1 watchersCompare

[ Source](https://github.com/rapiddive/nrql-builder)[ Packagist](https://packagist.org/packages/rapiddive/nrql-builder)[ RSS](/packages/rapiddive-nrql-builder/feed)WikiDiscussions main Synced yesterday

READMEChangelog (5)Dependencies (6)Versions (7)Used By (0)

NRQL Query Builder
==================

[](#nrql-query-builder)

[![CI](https://github.com/rapiddive/nrql-builder/actions/workflows/run-unit-test.yml/badge.svg)](https://github.com/rapiddive/nrql-builder/actions/workflows/run-unit-test.yml)

A PHP library for assembling [New Relic Query Language (NRQL)](https://docs.newrelic.com/docs/insights/new-relic-insights/using-new-relic-query-language/nrql-reference) queries in object-oriented applications.

The library implements the official NRQL specification and offers a fluent interface to specify query parts in an arbitrary order, allowing different application parts to influence a query without worrying about assembly order. Query integrity validation is performed upon rendering. Object-oriented representations for time expressions enable code completion and avoid typos.

Inspired by [upscalesoftware/newrelic-query-builder](https://github.com/upscalesoftware/newrelic-query-builder).

Requirements
------------

[](#requirements)

- PHP &gt;= 8.0
- [nesbot/carbon](https://carbon.nesbot.com/) ^3.11 (pulled in automatically via Composer)

Installation
------------

[](#installation)

```
composer require rapiddive/nrql-builder
```

Or add it to `composer.json` manually:

```
{
    "require": {
        "rapiddive/nrql-builder": "^2.0"
    }
}
```

Usage
-----

[](#usage)

### Full query

[](#full-query)

The example below demonstrates a query using all available clauses:

```
use Carbon\Carbon;
use Rapiddive\NrqlBuilder\Moment\ExactTime;
use Rapiddive\NrqlBuilder\Moment\TimeAgo;
use Rapiddive\NrqlBuilder\Moment\Yesterday;
use Rapiddive\NrqlBuilder\QueryBuilder;
use Rapiddive\NrqlBuilder\TimePeriod;

$nrql = (new QueryBuilder())
    ->select(['userAgentName'])
    ->from(['PageView'])
    ->where('userAgentOS = "Windows"')
    ->facet('countryCode')
    ->limit(20)
    ->since(new TimeAgo(new TimePeriod(4, TimePeriod::UNIT_DAYS)))
    ->until(new Yesterday())
    ->compareWith(new ExactTime(new Carbon('2015-01-01 00:00:00', 'UTC')))
    ->timeSeries(new TimePeriod(1, TimePeriod::UNIT_HOURS))
    ->withTimeZone('UTC');

echo $nrql;
// SELECT userAgentName FROM PageView WHERE userAgentOS = "Windows" FACET countryCode LIMIT 20 SINCE 4 days AGO UNTIL YESTERDAY COMPARE WITH '2015-01-01 00:00:00 UTC' TIMESERIES 1 hours WITH TIMEZONE 'UTC'
```

### Select all attributes

[](#select-all-attributes)

Use `selectAll()` as a shorthand for `SELECT *`:

```
$nrql = (new QueryBuilder())
    ->selectAll()
    ->from(['PageView']);

echo $nrql; // SELECT * FROM PageView
```

### Time series with auto bucket

[](#time-series-with-auto-bucket)

Call `timeSeries()` without a period to let New Relic choose the bucket size automatically:

```
$nrql = (new QueryBuilder())
    ->selectAll()
    ->from(['PageView'])
    ->timeSeries();

echo $nrql; // SELECT * FROM PageView TIMESERIES AUTO
```

### Reusing a builder as a template

[](#reusing-a-builder-as-a-template)

`resetPart()` clears a single clause so it can be reassigned, letting one builder serve as a base for multiple related queries:

```
$base = (new QueryBuilder())
    ->selectAll()
    ->from(['PageView'])
    ->where('userAgentOS = "Windows"');

echo $base; // SELECT * FROM PageView WHERE userAgentOS = "Windows"

$base->resetPart(QueryBuilder::PART_WHERE)->where('userAgentOS = "Mac"');

echo $base; // SELECT * FROM PageView WHERE userAgentOS = "Mac"
```

### Custom moment types

[](#custom-moment-types)

`since()`, `until()`, and `compareWith()` accept any implementation of `MomentInterface`, so you can define time expressions beyond the built-in `TimeAgo`, `Yesterday`, and `ExactTime`:

```
use Rapiddive\NrqlBuilder\Moment\MomentInterface;

class BeginningOfMonth implements MomentInterface
{
    public function renderNrql(): string
    {
        return "'" . date('Y-m-01 00:00:00') . " UTC'";
    }
}

$nrql = (new QueryBuilder())
    ->selectAll()
    ->from(['PageView'])
    ->since(new BeginningOfMonth());
```

API Reference
-------------

[](#api-reference)

### `QueryBuilder` clauses

[](#querybuilder-clauses)

MethodNRQL clauseNotes`select(array $attributes)``SELECT a, b`Comma-joins the array`selectAll()``SELECT *`Shorthand for wildcard`from(array $events)``FROM Event`Comma-joins the array`where(string $conditions)``WHERE ...`Raw condition string`facet(string $attribute)``FACET attr`Raw attribute string`limit(int $count)``LIMIT N`Throws on values &lt; 1`since(MomentInterface)``SINCE ...``until(MomentInterface)``UNTIL ...``compareWith(MomentInterface)``COMPARE WITH ...`Requires `SINCE` or `UNTIL``timeSeries(?TimePeriod, string $default='AUTO')``TIMESERIES ...``null` period uses `$default``withTimeZone(?string $timezone)``WITH TIMEZONE 'tz'`Value is auto-quoted`resetPart(string $part)`—Clears a clause for reassignmentUse the `QueryBuilder::PART_*` constants (e.g. `QueryBuilder::PART_WHERE`) when calling `resetPart()`.

### Time expressions (`Moment`)

[](#time-expressions-moment)

ClassRenders asConstructor`TimeAgo``N unit AGO``new TimeAgo(new TimePeriod(4, TimePeriod::UNIT_DAYS))``Yesterday``YESTERDAY``new Yesterday()``ExactTime``'Y-m-d H:i:s T'``new ExactTime(new Carbon('2024-01-01', 'UTC'))`### `TimePeriod` units

[](#timeperiod-units)

`TimePeriod::UNIT_MINUTES`, `UNIT_HOURS`, `UNIT_DAYS`, `UNIT_WEEKS`

Limitations
-----------

[](#limitations)

Some complex aspects of the NRQL syntax have not been implemented in an object-oriented manner. These include [Aggregator Functions](https://docs.newrelic.com/docs/insights/new-relic-insights/using-new-relic-query-language/nrql-reference#functions), [Math Operators](https://docs.newrelic.com/docs/insights/new-relic-insights/using-new-relic-query-language/nrql-math), and logical operators (`AND`, `OR`, grouping). The library accommodates these as free-format string arguments to `select()`, `where()`, and `facet()`.

License
-------

[](#license)

Licensed under the [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0).

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance97

Actively maintained with recent releases

Popularity8

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity49

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~164 days

Total

5

Last Release

16d ago

Major Versions

1.0.2 → 2.0.02026-06-14

PHP version history (2 changes)1.0.0PHP &gt;=8.0 | &gt;=7.4

2.0.0PHP &gt;=8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/3eb6cb36cb128b6bcd97e40cd881784a2cad0b1cd8f363f98edf5ffdf416c57a?d=identicon)[vinayshah5](/maintainers/vinayshah5)

---

Top Contributors

[![vinayshah](https://avatars.githubusercontent.com/u/4420182?v=4)](https://github.com/vinayshah "vinayshah (24 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/rapiddive-nrql-builder/health.svg)

```
[![Health](https://phpackages.com/badges/rapiddive-nrql-builder/health.svg)](https://phpackages.com/packages/rapiddive-nrql-builder)
```

###  Alternatives

[illuminate/support

The Illuminate Support package.

630113.0M41.3k](/packages/illuminate-support)[spatie/holidays

Calculate public holidays

402860.1k2](/packages/spatie-holidays)[craftcms/feed-me

Import content from XML, RSS, CSV or JSON feeds into entries, categories, Craft Commerce products, and more.

293952.6k33](/packages/craftcms-feed-me)[solspace/craft-freeform

The most flexible and user-friendly form building plugin!

54681.3k19](/packages/solspace-craft-freeform)[pimcore/data-importer

Adds a comprehensive import functionality to Pimcore Datahub

46855.5k5](/packages/pimcore-data-importer)[flarum/core

Delightfully simple forum software.

201.4M2.3k](/packages/flarum-core)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
