MongoDB text index required for $text query

Viewed 3352

I tried to find an answer to my question but i couldn't find anything with my specific problem. When i try to do a simple text search on my collection with TextCriteria i have the error :

Query failed with error code 27 and error message 'text index required for $text query'

I know for sure it is a mongo error on my part but i am not able to solve the problem.

Sample of my collection implementation :

@Document(collection = "mission")
@Getter
@Setter
@JsonInclude(Include.NON_NULL)
public class Mission {
    @Id
    @JsonProperty("_id")
    private String id;

    @JsonProperty("secteur")
    private String secteur;

    @JsonProperty("client")
    private String client;

    @Field
    @TextIndexed
    @JsonProperty("poste")
    private String poste;
    
    @Field
    @TextIndexed
    @JsonProperty("competences")
    private List<Competence> competences;

    @Field
    @TextIndexed
    @JsonProperty("description")
    private String description;

The method i use to retrieve my list :

@Override
public Collection<Mission> findAllByCriteria() {
    return missionDao.findAllBy(TextCriteria.forDefaultLanguage().matchingAny("angular"));
}
2 Answers

Does this specific collection have the appropriate text index created in the first place? Without knowing how the DB was created it's possible it doesn't and you'll have to create it yourself. If you're already using the same code to persist this entity into the DB then Mongo should create the text indexes for you.

See Mongo documentation on text indexes, and check this post.

If anyone else runs into this problem, try this property in application.yml:

spring:
  data:
    mongodb:
      auto-index-creation: true

Or in application.properties:

spring.data.mongodb.auto-index-creation=true

This way spring will automatically set the text index, and you don't need to use the shell.

Related