11

Here is my document:

@Document(collection = "posts")
public class Post {
    @Id
    String id;
    String title;
    String description;
}

I'm trying to query for posts with title or description with a like operator. My Repository

public class PostsRepository extends MongoRepository<Post, String> {
    @Query(value = "{ $or: [ { 'title' : ?0 }, { 'description' : ?0 } ] }")
    Page<Post> queryByTitleOrDescription(String query, Pageable pageable);
}

How do i perform this query with LIKE on both fields with an or between them?

2 Answers 2

12

You can even go without any explicit query declaration if needed:

interface PostRepository extends Repository<Post, String> {

  // A default query method needs parameters per criteria

  Page<Post> findByTitleLikeOrDescriptionLike(String title, 
                                              String description,
                                              Pageable pageable);

  // With a Java 8 default method you can lipstick the parameter binding 
  // to accept a single parameter only

  default Page<Post> findByTitleOrDescription(String candidate, Pageable pageable) {
    return findByTitleLikeOrDescriptionLike(candidate, candidate, pageable);
  }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Is it using the regex by default and not performing a full text comparison?
Super! Thanks a bunch.
8

So to answer my own question, this is the solution I came up with, if someone knows something which is more performant I'd appreciate it (I believe text search is not applicable since it doesn't work with partial words)

@Query(value = "{ $or: [ { 'title' : {$regex:?0,$options:'i'} }, { 'description' : {$regex:?0,$options:'i'} } ] }")
    Page<Post> query(String query, Pageable page);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.