简体   繁体   中英

Full text search on hstore field using index

Is it possible to do do a full text search on an hstore column which leverages the gin index?

I have a hstore column 'data' and an index like the docs say:

CREATE INDEX hidx ON testhstore USING GIN (data);

And as far as I can find the way to query over this is to cast with avals on the hstore column:

CAST(avals(data) AS text) @@ 'something'

However and explain query only does a scan and no index lookup, taking several seconds on a table with less than 100k records.

Yes, you can make a full-text index on any expression, not just a column.

eg:

CREATE INDEX someindex ON sometable USING gin(to_tsvector('english', CAST(avals(data) AS text)));

I recommend wrapping such expressions in simple SQL functions, like:

CREATE OR REPLACE FUNCTION hstore_vals_text(hstore)
RETURNS text LANGUAGE sql IMMUTABLE AS $$
SELECT CAST(avals($1) AS text);
$$;

CREATE INDEX someindex ON sometable USING gin(to_tsvector('english', hstore_vals_text(data)));

SELECT ... FROM ... WHERE hstore_vals_text(data) @@ to_tsquery('something');

This helps the parser match the index to the expression, as it's not super bright about figuring out which indexes match which expressions.

For best performance (at the cost of some wasted storage space) you may want to duplicate the data in a trigger-maintained column containing the tsvector and index that; see the tsearch2 documentation for how. You'd need to write your own trigger rather than use the generic one provided, though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM