Full Text Search
Full Text Search
Couchbase Lite [1] supports Full Text Search (FTS).
FTS is accomplished using the match query.
FTS matches are case-sensitive.
In the Travel App, the FTS query is against local "travel-sample" documents that is pre-built with the app.
In order to do FTS queries, an FTS index must be created.
Open the fileHotelsDao.java.
We will review the searchHotelsAsync() method.
This code snippet creates an FTS index on the property named description.
@Nonnull
private List<Hotel> searchHotelsAsync(@Nonnull String location, @Nonnull String desc) {
...
}
final ResultSet results = QueryBuilder
.select(SelectResult.expression(Meta.id), SelectResult.all())
.from(DataSource.database(db.getDatabase()))
.where(Expression.property(DbManager.PROP_DOC_TYPE).equalTo(Expression.string(Hotel.DOC_TYPE))
.and(FullTextExpression.index(DbManager.FTS_INDEX_DESC).match(desc)
.and(Expression.property(Hotel.PROP_ADDRESS).like(Expression.string(loc))
.or(Expression.property(Hotel.PROP_CITY).like(Expression.string(loc)))
.or(Expression.property(Hotel.PROP_STATE).like(Expression.string(loc)))
.or(Expression.property(Hotel.PROP_COUNTRY).like(Expression.string(loc))))))
.orderBy(Ordering.property(Hotel.PROP_NAME).ascending())
.execute();
This is a fairly involved query expression.
-
You will create an FTS
Expressionsusing thematch()operator. In this particular example, thematchexpression looks for thedescvalue in thedescriptionproperty. -
This
matchexpression is logically ANDed with anequalTocomparison expression which looks for thelocationin thecountry,city,stateoraddressproperties. -
This expression is then used in the
whereclause of the query the usual way.
We build the query using the different expressions from above and parse the ResultSet object into a List<Hotel> object
for (Result result : results.allResults()) {
if (result.count() < 2) { continue; }
final Hotel hotel = Hotel.fromDictionary(result.getString(0), result.getDictionary(1));
if (hotel != null) { hotels.add(hotel); }
}