Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lookups on texts, arrays and JSON

Besides the comparisons of Conditions, some column types have lookups of their own: searching in a text, testing what an array holds, looking inside JSON. This page lists them all, with the SQL each one sends.

Texts

Case-insensitive lookups

#![allow(unused)]
fn main() {
Station::name().iexact("rennes")         // → 2
Station::name().icontains("mat")         // → 5, Toulouse Matabiau
Station::name().istartswith("par")       // → 1, Paris Montparnasse
}
WHERE upper("t0"."name") = upper($1)       -- params: [Text("rennes")]
WHERE upper("t0"."name") LIKE upper($1)    -- params: [Text("%mat%")]
WHERE upper("t0"."name") LIKE upper($1)    -- params: [Text("par%")]

These are Django’s iexact, icontains and istartswith, written as Django writes them for PostgreSQL: with upper(…) on both sides, not with ILIKE. The rows are the same (but for a few rare letters), and in a database whose locale is not C, upper is faster: ILIKE lowercases both sides on every row.

The text you give is matched as it is: a % or a _ in it is a plain character, not a wildcard. So a search box can pass what the user typed.

An index that helps these lookups is a trigram index on the same expression (Indexes):

#![allow(unused)]
fn main() {
#[index(name = "network_station_name_trgm", sql = "USING gin (upper(name) gin_trgm_ops)")]
}

Your own patterns: like and ilike

#![allow(unused)]
fn main() {
Station::name().like("Paris %")          // → 1
Station::name().ilike("%CENTRALE")       // → 6, Milano Centrale
}
WHERE "t0"."name" LIKE $1     -- params: [Text("Paris %")]
WHERE "t0"."name" ILIKE $1    -- params: [Text("%CENTRALE")]

Here the pattern is yours: % is any text, _ is any one character. like is case-sensitive, ilike is not.

To put a user’s text inside your own pattern, escape it with like_escape, so that their % stays a %:

#![allow(unused)]
fn main() {
use rind::query::like_escape;

Station::name().like(format!("%{}%", like_escape("50%")))
// params: [Text("%50\\%%")]
}

This is also how to write a case-sensitive contains, startswith or endswith, which have no method of their own:

Djangorind
contains="x"like(format!("%{}%", like_escape(x)))
startswith="x"like(format!("{}%", like_escape(x)))
endswith="x"like(format!("%{}", like_escape(x)))
iendswith="x"ilike(format!("%{}", like_escape(x)))

Ignoring accents: unaccent

#![allow(unused)]
fn main() {
Station::city().unaccent().icontains("quimper")   // → 4
}
WHERE upper(unaccent("t0"."city")) LIKE upper($1)

.unaccent() turns a text path into an expression without accents, on which the same lookups work: “Finistère” then matches “finistere”. It uses PostgreSQL’s unaccent extension, which the domain must declare (domain!(…).extension("unaccent"), see Search). Without it, the query fails with function unaccent(character varying) does not exist.

Upper case: upper

#![allow(unused)]
fn main() {
Station::city().upper().eq("BREST")       // → 3
// WHERE upper("t0"."city") = $1
}

.upper() is an expression too, for your own comparisons.

Regular expressions

There is no method for a regular expression on a path. Write it with an expression template:

#![allow(unused)]
fn main() {
Station::code().expr().wrap::<bool>("({} ~ '^[A-Z]{3}$')").eq(true)
// WHERE ("t0"."code" ~ '^[A-Z]{3}$') = $1        -- params: [Bool(true)]
}

Put the parentheses in the template: rind copies it as it is, and the comparison that follows (= $1) must apply to the whole of it.

(A resource’s search has a regex mode, for a client’s search: Filters.)

Arrays

An array column (Vec<String>, Vec<i64>, Vec<i32>) has two lookups, those of Django’s ArrayField. The stations’ services: Paris has {wifi,lift,bikes}, Rennes {wifi,lift}, Brest {wifi}, Quimper {}, Toulouse {wifi,bikes}, Milano {lift}.

#![allow(unused)]
fn main() {
Station::services().contains(["wifi", "lift"])    // every one of them → 1, 2
Station::services().overlaps(["bikes", "lift"])   // at least one     → 1, 2, 5, 6
}
WHERE "t0"."services" @> $1    -- params: [TextArray(["wifi", "lift"])]
WHERE "t0"."services" && $1    -- params: [TextArray(["bikes", "lift"])]
rindSQLDjangoMatches when the column holds
contains(values)@>containsevery one of the values
overlaps(values)&&overlapat least one of the values
eq(vec)=exactexactly these, in this order

The values are sent as one array parameter. On an array of integers, they are i64, whatever the column’s width.

An empty array is an array like any other:

#![allow(unused)]
fn main() {
Station::services().eq(Vec::<String>::new())   // → 4, Quimper
}

To search inside the elements (a service whose name contains “bik”), turn the array into text with as_text(), then use a text lookup:

#![allow(unused)]
fn main() {
Station::services().as_text().icontains("bik")   // → 1, 5
// WHERE upper(CAST("t0"."services" AS text)) LIKE upper($1)
}

A GIN index serves contains and overlaps: #[index(name = "…", sql = "USING gin (services)")].

JSON

A jsonb column (serde_json::Value) has Django’s JSONField lookups. With a model Product whose column extra is {"colour": "red", "size": 42}:

#![allow(unused)]
fn main() {
Product::extra().has_key("colour")                  // ?   → the key is there
Product::extra().has_any_key(["colour", "weight"])  // ?|  → at least one is there
Product::extra().json_text("colour").eq("red")      // ->> → the text at a key
}
rindSQLDjango
has_key(k)extra ? 'k'extra__has_key="k"
has_any_key(ks)extra ?| array[…]extra__has_any_keys=[…]
json_text(k)extra ->> 'k', an expression of type Stringextra__k (as text)

json_text is an expression, so every text comparison and lookup works on it: json_text("colour").icontains("re"), .in_(["red", "blue"]). A key that is not there gives NULL.

An empty list in has_any_key matches nothing. Deeper paths (extra__dimensions__width) and contains on JSON have no method: write them with an expression template.

Geography

The PostGIS columns (Point, Polygon…) have their own conditions (within a distance, contains a point, intersects): see Geography.

Summary

ColumnMethods
textiexact, icontains, istartswith, like, ilike, .upper(), .unaccent(), and every comparison
arraycontains, overlaps, as_text(), eq
JSONhas_key, has_any_key, json_text(k)
geographysee Geography

Next: Following relations.