Sorting with UPPER and LOWER in Postgres - postgresql

I'm pretty new to postgres, and wanted to know how to sort my table using the upper(or lower) functions to make a case-insensitive search. I know I could do something along the lines of:
where b.name ~* '%Example%'
But that method makes my query a bit slow. So I wanted to try the following below.
Assume that table b is like this:
order | name
1 | Example
2 | example
3 | EXAMPLE
4 | ExAmPlE
Whenever I use the query:
set schema 'schem';
select UPPER(b.name),
from b
where b.name like UPPER('%Example%');
What it comes down to is the query itself. Whenever the where clause is:
where b.name like UPPER('%Example%');
Nothing displays.
where b.name like UPPER('%E%');
Example, EXAMPLE, and ExAmPlE show in all upper-case.
where b.name like UPPER('%EXAMPLE%');
Only EXAMPLE shows.
Maybe I'm not understanding postgres right, but does the upper function only show its parameter's data in all caps? What I thought was happening is that my query will take all of the examples, force them to all upper-case, and then the where clause will also be forced to upper-case, and therefore whenever I used any of the where clauses mentioned above, each of those queries would spit everything in table b.
Am I forced to having to use the format where b.name ~* '%Example%' or am I just misunderstanding this?

Postgresql strings are case sensitive and you need to use upper on columns if you want to match your upper() query.
If you want to search case insensitive, you can also use ILIKE instead of LIKE.
If you for some reason need to store case insensitive text, there is an extension citext.
There is not much difference between name LIKE '%argh%' and name ~* 'argh', these are basically the same the way we use them in this example. The ~* operator is however much more powerful as it is a case insensitive regular expression match. (Case sensitive is ~).
If you want to have a fast query where you filter on condition, you might want to reconsider if you can change condition in such a way to match the field at beginning. Then you can use normal btree index with upper:
create index b_name_idx on b (upper(name));
This is called functional index (because you use function), and in order for postgresql to use it you must also use upper on your field:
select * from b where upper(b.name) like 'argh%';
However, if you must check for containment, if searched string can be somewhere in the middle, you might want to use pg_trgm extension.
create extension pg_trgm;
create index b_name_trgmidx on b using gin (name gin_trgm_ops);
Then these both will be able to use index:
select * from b where b.name like '%argh%';
select * from b where b.name ~* 'argh';

Related

What is the correct way to create a case-insensitive trigram-index in postgres?

...and is it something I should do anyway?
From my brief testing, making a trigram index and searching using
where name like '%query%'
is faster than
where name ilike '%query%'
So it seems like I should do it, but I'm surprised I've not been able to find out how.
(My test data is fairly homogenous - 1.5M rows made up of 16 entries repeated. I can imagine this might mess with the results.)
This is how I expected it to work (note the lower(name)):
create extension pg_trgm;
create table users(name text);
insert into users values('Barry');
create index "idx" on users using gin (lower(name) gin_trgm_ops);
select count(*) from users where (name like '%bar%');
but this returns 0.
Either of
select count(*) from users where (name like '%Bar%');
or
select count(*) from users where (name ilike '%bar%');
work, which makes me believe the trigrams in the index are not lower()'d. Am I misunderstanding how this works under the hood? Is it not possible to call lower there?
I note that this
select show_trgm('Barry')
returns lowercase trigrams:
{" b"," ba",arr,bar,rry,"ry "}
So I'm perplexed.
The trigrams are definitely lower case.
The conundrum becomes cleared up when you consider how trigram indexes are used: they act as a filter that eliminates the majority of non-matches, but allow false positive results (among other reasons is their case insensitivity). That's why there always has to be a recheck to eliminate those false positives, and that us why you always get a bitmap index scan.
The ILIKE query may be slower because it has more results, or because case insensitive comparisons require more effort.

Postgresql: how to set a weight for tsquery

How to set a weight for tsquery? I need to set a weight for tsquery obtained from plainto_tsquery.
Is it possible? Something like setweight(plainto_tsquery(''), 'A'), but it works only for tsvector.
I have this problem too. My use case is large documents, many sections, and I wish to provide an option for "search heading text only". (Headings have weight A and are scattered throughout the document; other sections have weight B, C or D depending upon where they occur.)
Here are two solutions that should help.
Solution 1: setweight function for tsquery
The function converts the tsquery to text, applies a regular expression to set the weights, then coverts back to tsquery.
CREATE FUNCTION setweight(query tsquery, weights text) RETURNS tsquery AS $$
SELECT regexp_replace(
query::text,
'(?<=[^ !])'':?(\*?)A?B?C?D?', ''':\1'||weights,
'g'
)::tsquery;
$$ LANGUAGE SQL IMMUTABLE;
Example:
select setweight( plainto_tsquery('fat cats and rats'), 'A' );
-- 'fat':A & 'cat':A & 'rat':A
select setweight( phraseto_tsquery('fat cats and rats'), 'A' );
-- 'fat':A <-> 'cat':A <2> 'rat':A
select setweight( to_tsquery('fat & (cat:A & rat) & !dog:*CD'), 'BC' );
-- 'fat':BC & 'cat':BC & 'rat':BC & !'dog':*BC
Solution 2: Functional index based on filtered tsvector
First create additional indexes on the fulltext column you'll be searching on.
e.g.
CREATE INDEX fulltext_idx
ON your_table USING gin
(fulltext)
CREATE INDEX fulltext_idx_A
ON your_table USING gin
(ts_filter(fulltext, '{a}'))
CREATE INDEX fulltext_idx_AB
ON your_table USING gin
(ts_filter(fulltext, '{a,b}'))
For whatever combination of weights you need.
Then, when searching, use the filtered expression. e.g.:
SELECT *
FROM your_table
WHERE ts_filter(fulltext, '{a}') ## plainto_tsquery('your query')
The search should take place on the indexed expression.
Discussion
Solution 1 gives you the function you're looking for, but the problem with weighted queries is that although postgres will use the index to find candidate matches, it still needs to pull back each document to check the weights.
In my case, when searching by titles only, Solution 2 appears to give better performance. The text within titles (weight A) uses a much smaller vocabulary than in the whole document, so the fulltext_idx_A is considerably smaller than fulltext_idx and the results don't need rechecked after matching.
For your own case, performance will depend entirely on your own document structure and the nature of your queries, so test using 'explain analyse' to select the better solution. Given the age of the ticket mind you, I assume you've solved this one already :-)
Note: ts_filter() and phraseto_tsquery() are from Postgres 9.6.
Here is the Best article about Postgres Full Text Search :
https://www.compose.com/articles/mastering-postgresql-tools-full-text-search-and-phrase-search/
and you can also set weight by using :
setweight(to_tsvector(coalesce($columnName, '')), '$weight')
Where column name something like users.name (table.column)
And Weight you want E.g A, B or C

Searching individual words in a string

I know about full-text search, but that only matches your query against individual words. I want to select strings that contain a word that starts with words in my query. For example, if I search:
appl
the following should match:
a really nice application
apples are cool
appliances
since all those strings contains words that start with appl. In addition, it would be nice if I could select the number of words that match, and sort based on that.
How can I implement this in PostgreSQL?
Prefix matching with Full Text Search
FTS supports prefix matching. Your query works like this:
SELECT * FROM tbl
WHERE to_tsvector('simple', string) ## to_tsquery('simple', 'appl:*');
Note the appended :* in the tsquery. This can use an index.
See:
Get partial match from GIN indexed TSVECTOR column
Alternative with regular expressions
SELECT * FROM tbl
WHERE string ~ '\mappl';
Quoting the manual here:
\m .. matches only at the beginning of a word
To order by the count of matches, you could use regexp_matches()
SELECT tbl_id, count(*) AS matches
FROM (
SELECT tbl_id, regexp_matches(string, '\mappl', 'g')
FROM tbl
WHERE string ~ '\mappl'
) sub
GROUP BY tbl_id
ORDER BY matches DESC;
Or regexp_split_to_table():
SELECT tbl_id, string, count(*) - 1 AS matches
FROM (
SELECT tbl_id, string, regexp_split_to_table(string, '\mappl')
FROM tbl
WHERE string ~ '\mappl'
) sub
GROUP BY 1, 2
ORDER BY 3 DESC, 2, 1;
db<>fiddle here
Old sqlfiddle
Postgres 9.3 or later has index support for simple regular expressions with a trigram GIN or GiST index. The release notes for Postgres 9.3:
Add support for indexing of regular-expression searches in pg_trgm
(Alexander Korotkov)
See:
PostgreSQL LIKE query performance variations
Depesz wrote a blog about index support for regular expressions.
SELECT * FROM some_table WHERE some_field LIKE 'appl%' OR some_field LIKE '% appl%';
As for counting the number of words that match, I believe that would be too expensive to do dynamically in postgres (though maybe someone else knows better). One way you could do it is by writing a function that counts occurrences in a string, and then add ORDER BY myFunction('appl', some_field). Again though, this method is VERY expensive (i.e. slow) and not recommended.
For things like that, you should probably use a separate/complimentary full-text search engine like Sphinx Search (google it), which is specialized for that sort of thing.
An alternative to that, is to have another table that contains keywords and the number of occurrences of those keywords in each string. This means you need to store each phrase you have (e.g. really really nice application) and also store the keywords in another table (i.e. really, 2, nice, 1, application, 1) and link that keyword table to your full-phrase table. This means that you would have to break up strings into keywords as they are entered into your database and store them in two places. This is a typical space vs speed trade-off.

Postgresql ILIKE versus TSEARCH

I have a query with a number of test fields something like this:
SELECT * FROM some-table
WHERE field1 ILIKE "%thing%"
OR field2 ILIKE "%thing"
OR field3 ILIKE "%thing";
The columns are pretty much all varchar(50) or thereabouts. Now I understand to improve performance I should index the fields upon which the search operates. Should I be considering replacing ILIKE with TSEARCH completely?
A full text search setup is not identical to a "contains" like query. It stems words etc so you can match "cars" against "car".
If you really want a fast ILIKE then no standard database index or FTS will help. Fortunately, the pg_trgm module can do that.
http://www.postgresql.org/docs/9.1/static/pgtrgm.html
http://www.depesz.com/2011/02/19/waiting-for-9-1-faster-likeilike/
One thing that is very important: NO B-TREE INDEX will ever improve this kind of search:
where field ilike '%SOMETHING%'
What I am saying is that if you do a:
create index idx_name on some_table(field);
The only access you will improve is where field like 'something%'. (when you search for values starting with some literal). So, you will get no benefit by adding a regular index to field column in this case.
If you need to improve your search response time, definitely consider using FULL TEXT SEARCH.
Adding a bit to what the others have said.
First you can't really use an index based on a value in the middle of the string. Indexes are tree searches generally, and you have no way to know if your search will be faster than just scanning the table, so PostgreSQL will default to a seq scan. Indexes will only be used if they match the first part of the string. So:
SELECT * FROM invoice
WHERE invoice_number like 'INV-2012-435%'
may use an index but like '%44354456%' cannot.
In general in LedgerSMB we use both, depending on what kind of search we are doing. You might see a search like:
select * from parts
WHERE partnumber ilike ? || '%'
and plainto_tsquery(get_default_language(), ?) ## description;
So these are very different. Use each one where it makes the most sense.

Matching patterns between multiple columns

I have two columns say Main and Sub. (they can be of same table or not).
Main is varchar of length 20 and Sub is varchar of length 8.
Sub is always subset of Main and it is last 8 characters of Main.
I could successfully design a query to match pattern using substr("Main",13,8)
Query:
select * from "MainTable"
where substr("MainColumn",13,8) LIKE (
select "SubColumn" From "SubTable" Where "SubId"=1043);
but I want to use Like, % , _ etc in my query so that I can loosely match the pattern (that is not all 8 characters).
Question is how can i do that.?!
I know that the query below is COMPLETELY WRONG but I want to achieve something like this,
Select * from "MainTable"
Where "MainColumn" Like '%' Select "SubColumn" From "SubTable" Where "SubId"=2'
The answers so far fail to address your question:
but I want use Like, % , _ etc in my query so that I can loosely match
the pattern (that is not all 8 characters).
It makes hardly any difference whether you use LIKE or = as long as you match the whole string (and there are no wildcard character in your string). To make the search fuzzy, you need to replace part of the pattern, not just add to it.
For instance, to match on the last 7 (instead of 8) characters of subcolumn:
SELECT *
FROM maintable m
WHERE left(maincolumn, 8) LIKE
( '%' || left((SELECT subcolumn FROM subtable WHERE subid = 2), 7));
I use the simpler left() (introduced with Postgres 9.1).
You could simplify this to:
SELECT *
FROM maintable m
WHERE left(maincolumn, 7) =
(SELECT left(subcolumn,7) FROM subtable WHERE subid = 2);
But you wouldn't if you use the special index I mention further down, because expressions in functional indexes have to matched precisely to be of use.
You may be interested in the extension pg_tgrm.
In PostgreSQL 9.1 run once per database:
CREATE EXTENSION pg_tgrm;
Two reasons:
It supplies the similarity operator %. With it you can build a smart similarity search:
--SELECT show_limit();
SELECT set_limit(0.5); -- adjust similarity limit for % operator
SELECT *
FROM maintable m
WHERE left(maincolumn, 8) %
(SELECT subcolumn FROM subtable WHERE subid = 2);
It supplies index support for both LIKE and %
If read performance is more important than write performance, I suggest you create a functional GIN or GiST index like this:
CREATE INDEX maintable_maincol_tgrm_idx ON maintable
USING gist (left(maincolumn, 8) gist_trgm_ops);
This index supports either query. Be aware that it comes with some cost for write operations.
A quick benchmark for a similar case in this related answer.
Try
SELECT t1.* from "Main Table" AS t1, "SubTable" AS t2
WHERE t2.SubId=1043
AND substr(t1.MainColumn, 13, 8) LIKE "%" || CAST(t2.SubColumn as text);
Argument to a LIKE is an ordinary string, so all string manipulations are valid here.
In your case you need to concatenate wildchars with the target substring, like #bksi suggests:
... LIKE '%'||CAST("SubColumn" AS test) ...
Note, though, that such patterns (the ones starting with a % wildcard) are badly performing ones. Take a look at PostgreSQL LIKE query performance variations.
I would recommend:
sticking with the current substr("MainColumn", 13, 8) approach;
avoid LIKE and use equality comparison (=) instead (although they're equal if LIKE pattern contains no wildcards, it is easier to read the query);
build an expression index on the "MainTable" the following way:
CREATE INDEX i_maincolumn ON "MainTable" (substr("MainColumn", 13, 8));
This combination will perform better in my view.
And use lowercase names for the tables/columns, so that you can avoid doublequoting them.