The Best way to use ElasticSearch in Spring java framework

前端 未结 4 1970
梦谈多话
梦谈多话 2021-01-31 04:24

I\'m developing a system which is planning to use elasticsearch as an data repository. I\'m trying to choose the best way to develop my application that can index and query data

4条回答
  •  别跟我提以往
    2021-01-31 05:17

    Spring data elasticsearch supports most of the common feature set of elasticsearch including Nested, Inner Objects and Parent Child (recently).

    When you said that want to use nested data (inner object), please be clear as elasticsearch has two concepts: Inner Object and Nested Object.

    Detailed explanation can be found at managing relationship in elasticsearch

    Nested document Example

    Person Entity:

    @Document(indexName = "person" , type = "user")
    
    public class Person {
    
        @Id
        private String id;
    
        private String name;
    
        @Field( type = FieldType.Nested)
        private List car;
    
        // setters-getters
    }
    

    Car Entity:

    public class Car {
        private String name;
        private String model;
        //setters and getters 
    }
    

    Setting up data:

    Person foo = new Person();
    foo.setName("Foo");
    foo.setId("1");
    
    List cars = new ArrayList();
    Car subaru = new Car();
    subaru.setName("Subaru");
    subaru.setModel("Imprezza");
    cars.add(subaru);
    foo.setCar(cars);
    

    Indexing:

    IndexQuery indexQuery = new IndexQuery();
    indexQuery.setId(foo.getId());
    indexQuery.setObject(foo);
    
    //creating mapping
    elasticsearchTemplate.putMapping(Person.class);
    //indexing document
    elasticsearchTemplate.index(indexQuery);
    //refresh
    elasticsearchTemplate.refresh(Person.class, true);
    

    Searching:

    QueryBuilder builder = nestedQuery("car", boolQuery()
        .must(termQuery("car.name", "subaru"))
        .must(termQuery("car.model", "imprezza")));
    
    SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build();
    List persons = elasticsearchTemplate.queryForList(searchQuery, Person.class);
    

    You can find more test cases about Nested and Inner Object at Nested Object Tests

提交回复
热议问题