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?
Related
I have a problem, I need to count the frequency of a word phrase appearing within a text field in a PostgreSQL database.
I'm aware of functions such as to_tsquery() and I'm using it to check if a phrase exists within the text using to_tsquery('simple', 'sample text'), however, I'm unsure of how to count these occurrences accurately.
If the words are contained just once in the string (I am supposing here that your table contains two columns, one with an id and another with a text column called my_text):
SELECT
count(id)
FROM
my_table
WHERE
my_text ~* 'the_words_i_am_looking_for'
If the occurrences are more than one per field, this nested query can be used:
SELECT
id,
count(matches) as matches
FROM (
SELECT
id,
regexp_matches(my_text, 'the_words_i_am_looking_for', 'g') as matches
FROM
my_table
) t
GROUP BY 1
The syntax of this function and much more about string pattern matching can be found here.
I want to match all exact match including:
- Exact match
- Plurals
- Mispelling
Table data:
natural loofah (YES - Exact match)
natural loofahs (YES - Exact match with plural)
natural lofah (YES - Exact match with misspelling)
Loofah natural (NO)
all natural loofah (NO - It's not exact match)
I tried with this but its not working
SELECT
query
FROM reports
WHERE to_tsvector('english', query) ## websearch_to_tsquery('english', 'natural loofah')
GROUP BY query
No this won't work. You have misunderstood what full text search does: it searches for whole words (optional: prefixes), ignoring flexion.
Full text search does not search for similarity.
Maybe you'd be better off with a trigram index:
CREATE EXTENSION pg_trgm;
CREATE INDEX ON reports USING gin (query gin_trgm_ops);
SELECT query
FROM reports
WHERE query % 'natural loofah';
Here % is the similarity operator.
As an alternative to trigram search, Postgres also has a text processor called 'simple' that will leave in stopwords and not perform any stemming on the search terms. This will let you do exact phrase matches on your query document, just be aware of what you lose in building a search index with 'simple'.
# select * from websearch_to_tsquery('english', '"eats, shoots, and leaves"');
websearch_to_tsquery
------------------------------
'eat' <-> 'shoot' <2> 'leav'
(1 row)
# select * from websearch_to_tsquery('simple', '"eats, shoots, and leaves"');
websearch_to_tsquery
--------------------------------------------
'eats' <-> 'shoots' <-> 'and' <-> 'leaves'
(1 row)
I have a posts that has a column tags. I'd like to be able to do full text search across the tags. For VARCHAR columns I've used:
CREATE INDEX posts_fts_idx ON posts USING gin(to_tsvector('english', coalesce(title, ''));
SELECT "posts".* FROM "posts" WHERE (to_tsvector('english', coalesce(title, '')) ## (to_tsquery('english', 'ruby')));
However, for character varying[] the function to_tsvector does not exist. How can a query be written that will run against each of the tags (ideally matching if any single tag matches)?
Note: I see that it would be pretty easy to do a conversion to a string (array_to_string) but if possible I'd like to convert each individual tag to a tsvector.
You could index the character varying using gin for search options. Try this :
CREATE INDEX idx_post_tag ON posts USING GIN(tags);
SELECT * FROM posts WHERE tags #> (ARRAY['search string'::character varying]);
This is when an exact match is desired. If an exact match is not desired, you should consider storing your tags as a text column. Think more on the significance of these 'tags'. String array types lack text indexing, stemming and inflection support, and hence you won't be able to match bates such as 'Dancing' with 'Dance'.
If that is not an option, you could circumvent this with an immutable version of array_to_string function. Your queries would then be :
CREATE INDEX posts_fts_idx ON posts USING gin(to_tsvector('english', immutable_array_to_string(tags, ' ')));
SELECT "posts".* FROM "posts" WHERE (to_tsvector('english', immutable_array_to_string(tags, ' ')) ## (to_tsquery('english', 'ruby')));
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.
I need to store a few hundred thousand HTML documents in a database and be able to search them. But not just for content - I need the searches to match class names, script names and id values (among other things) that might appear as attributes within the HTML tags in the documents. I tried using to_tsvector('english', tableColumn) and to_tsvector('simple', tableColumn) but neither seem to match the contents of attributes in tags. Specifically, I did this:
create index an_index on myTable using gin (to_tsvector('simple',tableColumn))
and then:
select url from myTable where to_tsvector ('simple', tableContent) ## to_tsquery ('myscript.js')
I expected it to retrieve all documents that contained a reference to myscript.js. But it returns no results.
Is it possible to achieve the results I want using the full-text search?
Thanks in advance for your help.
Try instead.
SELECT url FROM myTable WHERE tableColumn ## to_tsquery ('simple','myscript.js')