Spring-data-elasticsearch嵌套查询不起作用

时间:2015-02-05 09:18:30

标签: java elasticsearch spring-data-elasticsearch

Person.java

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

    @Id
    private String id;

    @Field(type = FieldType.String)
    private String name;

    @Field(type = FieldType.Nested)
    private List<Car> cars;

// getter/setter

}

Car.java

public class Car {

    @Field(type = FieldType.String)
    private String name;

    @Field(type = FieldType.String)
    private String model;

// getter/setter
}

使用main方法索引和搜索

public class SpringElasticSearchTest {

    public static void main(String[] args) {

        ApplicationContext applicationContext = new FileSystemXmlApplicationContext(
                "src/main/webapp/WEB-INF/spring/applicationContext.xml");

        ElasticsearchTemplate est = (ElasticsearchTemplate) applicationContext
                .getBean("elasticsearchTemplate");

        Person pers = new Person();
        pers.setName("Manish");
        pers.setId("1");

        List<Car> cars = new ArrayList<Car>();
        Car subaru = new Car();
        subaru.setName("Tata");
        subaru.setModel("Safari");
        cars.add(subaru);
        pers.setCars(cars);

        IndexQuery indexQuery = new IndexQuery();
        indexQuery.setId(pers.getId());
        indexQuery.setObject(pers);

        est.deleteIndex("person");

        est.createIndex(Person.class);
        est.putMapping(Person.class);
        est.index(indexQuery);
        est.refresh(Person.class, true);

        QueryBuilder builder = nestedQuery(
                "cars",
                boolQuery().must(termQuery("cars.name", "Tata")).must(
                        termQuery("cars.model", "Safari")));
        SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(
                builder).build();
        List<Person> persons = est.queryForList(searchQuery, Person.class);
        System.out.println("Person List : " + persons);

    }

索引工作正常,但功能搜索无法正常工作 我得到以下输出:

  

人员名单:[]

请建议。 提前谢谢。

2 个答案:

答案 0 :(得分:2)

最后我找到了解决方案,我在搜索时构建的查询

termQuery("cars.name", "Tata")

应为小写,因此正确的查询将是 -

QueryBuilder builder = nestedQuery(
                "cars",
                boolQuery().must(termQuery("cars.name", "tata")).must(
                        termQuery("cars.model", "safari")));

答案 1 :(得分:0)

另一种选择是使用matchQuery,默认情况下不区分大小写:

QueryBuilders.matchQuery("cars.name", "Tata")

或者您可以使用不会降低外壳的分析仪,与标准分析仪不同。

此处的相关讨论:https://discuss.elastic.co/t/how-to-do-case-insensitive-search-on-terms/19790