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.
Related
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
I'm trying to create a PostgreSQL query to find a partial text inside a tsvector column.
I have a tsvector value like this "'89' 'TT7' 'test123'" and I need to find any rows that contains "%es%".
How can I do that?
I tried
select * from use_docs_conteudo
WHERE textodados ## to_tsquery('es')
It looks like you want to use fast ILIKE queries for wild match. pg_trgm will be the right tool to go with. You can use POSIX regex rules for defining your query.
WITH data(t) AS ( VALUES
('test123! TT7 89'::TEXT),
('test123, TT7 89'::TEXT),
('test#test123.domain TT7 89'::TEXT)
)
SELECT count(*) FROM data WHERE t ~* 'es' AND t ~* '\mtest123\M';
Result:
count
-------
3
(1 row)
Links for existing answers:
Postgresql full text search part of words
PostgreSQL: Full Text Search - How to search partial words?
I have a table which contains a text column, say vehicle number.
Now I want to query the table for fields which contain a particular vehicle number.
While matching I do not want to consider non-alphanumeric characters.
example: query condition - DEL123
should match - DEL-123, DEL/123, DEL#123, etc...
If you know which characters to skip, put them as the second parameter of this translate() call (which is faster than regexp functions):
select *
from a_table
where translate(code, '-/#', '') = 'DEL123';
Else, you can compare only alphanumeric characters using regexp_replace():
select *
from a_table
where regexp_replace(code, '[^[:alnum:]]', '', 'g') = 'DEL123';
#klin's answer is great, but is not sargable, so in cases where you're searching through millions of records (maybe not your case, but perhaps someone else with a similar question looking for answers), using regular expressions will likely render much better results.
The following will use indexes on code significantly reducing the number of rows tested:
select *
from a_table
where code ~ '^DEL[^[:alnum:]]*123$';
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.
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.