Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine a Spring Data MongoDB Query with full text search?

I've recently upgraded to Spring Data MongoDB 1.6.0.RC1, which is very good and implements the full text search feature of MongoDB 2.6 (huuurah!). My question is: how can I combine the Criteria and TextCriteria classes to generate complex queries ?

Example object model:

{
  textProperty: "a text that is indexed for full text search",
  language:"en",
  aBooleanProperty: true,
  anIntegerProperty: 1
}

Query:

db.collection({ anIntegerProperty: 1,  $text: { $search: "indexed", $language: "en" } })

So, how can I write the above query with Spring Data MongoDB classes?

like image 973
morwed Avatar asked Aug 28 '14 14:08

morwed


1 Answers

Note: this post had non working code previously but is now fixed!

A TextCriteria is a CriteriaDefinition and thus can be used with a Query like this:

Quer query = Query.query(
  Criteria.where("aBooleanProperty").is(true).
  and(anIntegerProperty).is(1)).
  addCriteria(TextCriteria.
    forLanguage("en"). // effectively the same as forDefaultLanguage() here
    matching("a text that is indexed for full text search")));

List<YourDocumentType> result = mongoTemplate.findAll(query. YourDocumentType.class);

Polish this up by using static imports for Query.query and Criteria.where and it reads pretty fluent.

like image 164
Oliver Drotbohm Avatar answered Sep 28 '22 05:09

Oliver Drotbohm