Vijay Mohan
Vijay Mohan

Reputation: 1066

Spring Data ElasticSearch Build In IN query returning partial match

I am new to elastic search spring data, Today I was trying to get In query working with Spring data ES repository.

I have to do a lookup for list of user names, and if its exactly match in the index, need to get those users back as result.

I tried to use the built in repository 'In' method to do so, but it returns partial matches, please help me to make this working like SQL IN query.

Here is my repository code:

public interface UserRepository extends ElasticsearchRepository<EsUser, String>
{
    public List<EsUser> findByUserAccountUserNameIn(Collection<String> terms);
}

REQUEST:

{"terms":["vijay", "arun"], "type":"NAME"}

RESPONSE:

[
  {
    "userId": "236000",
    "fbId": "",
    "userAccount": {
      "userName": "arun",
      "urlFriendlyName": "arun",
    },
    "userProfile": {
    },
    "userStats": {
    }
  },
  {
    "userId": "6228",
    "userAccount": {
      "userName": "vijay",
      "urlFriendlyName": "vijay",
    },
    "userProfile": {
    },
    "userStats": {
    }
  },
  {
    "userId": "236000",
    "fbId": "",
    "userAccount": {
      "userName": "arun singh",
      "urlFriendlyName": "arun-singh",
    },
    "userProfile": {
    },
    "userStats": {
    }
  }
  {
    "userId": "236000",
    "fbId": "",
    "userAccount": {
      "userName": "vijay mohan",
      "urlFriendlyName": "vijay-mohan",
    },
    "userProfile": {
    },
    "userStats": {
    }
  }
 ]

Upvotes: 1

Views: 642

Answers (1)

Val
Val

Reputation: 217554

This is because your userAccount.userName field is an analyzed string, and thus, the two tokens arun and singh have been indexed. Your query then matches the first token, which is normal.

In order to prevent this and guarantee an exact match you need to declare your field as not_analyzed, like this:

@Field(index = FieldIndex.not_analyzed)
private String userName;

Then you'll need to delete your index and the associated template in /_template, restart your application so a new template and index are created with the proper field mapping.

Then your query will work.

Upvotes: 1

Related Questions