3
SELECT * FROM my_table WHERE product MATCH "apple";

returns: apple, green apple, apple jam ... I need FTS query that returns only "apple". These work slow:

SELECT * FROM my_table WHERE product="apple";
SELECT * FROM my_table WHERE product LIKE "apple";
user171435
  • 41
  • 1
  • 3

3 Answers3

2

With FTS tables, the only efficient queries are searches with MATCH.

With FTS4, you can restrict a search to the beginning of a document with ^:

SELECT * FROM my_table WHERE product MATCH '^apple';

However, this does not help for the end.

To do an efficient check for the entire column, do an FTS search first, then check the result of that:

SELECT *
FROM (SELECT product
      FROM my_table
      WHERE product MATCH '^apple')
WHERE product = 'apple';
CL.
  • 173,858
  • 17
  • 217
  • 259
  • Works like a charm! A suggestion would be to use `SELECT * FROM my_table WHERE product MATCH '^apple'` as sub query to get all the columns which apparently is the requirement of OP. Thanks! +1 – Shahood ul Hassan Apr 06 '19 at 07:17
  • Oh, another suggestion: we have to check for the case as well in main query. So, the final query incorporating both the suggestions would be as follows: `SELECT * FROM (SELECT * FROM my_table WHERE product MATCH '^apple') WHERE LOWER(product) = 'apple';`. Hope it still helps someone even after 04 years since this answer was posted. – Shahood ul Hassan Apr 06 '19 at 07:49
  • Not sure if it's suppoorted everywhere, but the `\b` marker means "word boundary", so `\bapple\b` would do. – Michał Leon Feb 04 '20 at 09:30
0

The purpose of FTS (full text search) is to find all exact and partial matches. When you search for "apple", it is expected to find apple, green apple, apple jam, apple11, apple123 (all the words starting with "apple" or phrases including the whole word "apple").

If you want to further narrow down the results, you could save the results in a temp table on the db side and search the temp table for exact match. Or you could also do this job on the client side:

DataTable dt = dbHelper.GetProducts(params);

string exactProductName = "apple";

// delete products from the table which are not an exact match
for (int i = dt.Rows.Count - 1; i >= 0; i--)
{
   DataRow dr = dt.Rows[i];
   if (dr["product"].ToString() != exactProductName )
      dr.Delete();
}

dt.AcceptChanges();
// now your data table includes only the exact match
ZP007
  • 582
  • 7
  • 12
-2

change the sql like this

SELECT *
FROM my_table
WHERE product MATCH '^apple$'

this sql means find the terms which start with apple and end with apple.

Jimmy Chen
  • 177
  • 5