1

人.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

}

汽车.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);

    }

索引工作正常,但搜索功能不起作用。
我得到以下输出:

人员名单:[]

请建议。提前致谢。

4

2 回答 2

3

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

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

应该是小写的,所以正确的查询是 -

QueryBuilder builder = nestedQuery(
                "cars",
                boolQuery().must(termQuery("cars.name", "tata")).must(
                        termQuery("cars.model", "safari")));
于 2015-02-06T02:56:20.033 回答
0

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

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

或者您可以使用不小写的分析器,这与标准分析器不同。

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

于 2015-09-29T09:00:09.017 回答