Spring Elasticsearch模板自定义字段名称

时间:2017-01-17 05:15:26

标签: java spring elasticsearch spring-data-elasticsearch

我正在使用Spring-Data-Elasticsearch来查询我的弹性搜索服务器。

这是我的数据和代码:

Elasticsearch:

{
  "user" : {
    "mappings" : {
      "user" : {
        "properties" : {
          "id" : { "type" : "long" },
          "first_name" : { "type" : "string" },
          "last_name" : { "type" : "string" }
        }
      }
    }
  }
}

Java模型:

@Document(indexName = "user", type = "user")
public class User {

    @Id
    private Long id;

    @JsonProperty("first_name")
    private String firstName;

    @JsonProperty("last_name")
    private String lastName;
}

Java存储库:

public class UserRepository extends ElasticsearchRepository<User, Long> {

    List<User> findByFirstName(String firstName);

    List<User> findByLastName(String LastName);
}

Java测试用例:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations="classpath:dispatcher-servlet.xml")
public class ElasticsearchTest {

    @Autowired
    private UserRepository repository;

    @Test
    public void test() throws Exception {
        User user1 = repository.findOne(1L);
        System.out.println(user1);

        List<User> users1 = repository.findByFirstName("Jack");
        System.out.println(users1);

        List<User> users2 = repository.findByLastName("Lin");
        System.out.println(users2);
    }
}

输出:

用户1:

User(id=1, firstName=Jack, lastName=Lin)

用户1:

[]

users2:

[]

和Elasticsearch模板DEBUG信息:

12:33:13,381 DEBUG ElasticsearchTemplate [main]:325 - doSearch query:
{
  "from" : 0,
  "size" : 1,
  "query" : {
    "bool" : {
      "must" : {
        "query_string" : {
          "query" : "Jack",
          "fields" : [ "firstName" ],
          "default_operator" : "and"
        }
      }
    }
  }
}

12:33:13,392 DEBUG ElasticsearchTemplate [main]:325 - doSearch query:
{
  "from" : 0,
  "size" : 1,
  "query" : {
    "bool" : {
      "must" : {
        "query_string" : {
          "query" : "Lin",
          "fields" : [ "lastName" ],
          "default_operator" : "and"
        }
      }
    }
  }
}

但在我的弹性搜索中,字段名称为first_namelast_name,我在模型中使用@JsonProperty,但它在ElasticsearchTemplate中不起作用。

为什么......?

0 个答案:

没有答案