Repository: SpringDataElasticsearchDevs/spring-data-elasticsearch-sample-application Branch: master Commit: d8162db10968 Files: 32 Total size: 76.0 KB Directory structure: gitextract_87k2jano/ ├── .gitignore ├── README.md ├── pom.xml └── src/ ├── main/ │ └── java/ │ └── org/ │ └── springframework/ │ └── data/ │ └── elasticsearch/ │ ├── entities/ │ │ ├── Article.java │ │ ├── ArticleBuilder.java │ │ ├── Author.java │ │ ├── Book.java │ │ ├── Car.java │ │ ├── GirlFriend.java │ │ ├── OperationDocument.java │ │ ├── Person.java │ │ ├── PersonMultipleLevelNested.java │ │ ├── Product.java │ │ └── Sector.java │ └── repositories/ │ ├── OperationDocumentRepository.java │ ├── SampleArticleRepository.java │ ├── SampleProductRepository.java │ └── book/ │ └── SampleBookRepository.java └── test/ ├── java/ │ └── org/ │ └── springframework/ │ └── data/ │ └── elasticsearch/ │ ├── ComplexNestedTypeContactTests.java │ ├── entities/ │ │ ├── Contact.java │ │ ├── Manuscript.java │ │ └── Role.java │ └── repositories/ │ ├── ElasticsearchFacetTests.java │ ├── NestedObjectTests.java │ ├── OperationDocumentRepositoryTest.java │ ├── SampleArticleRepositoryTest.java │ ├── SampleBookRepositoryTest.java │ └── SampleProductRepositoryTest.java └── resources/ ├── contact-test.xml ├── spring-context.xml ├── springContext-book-test.xml └── springContext-test.xml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ atlassian-ide-plugin.xml ## Ignore svn files .svn ## ignore any target dir target ##ignore only top level data dir - local node data files for unit tests /data ## Ignore project files created by Eclipse .settings .project .classpath ## Ignore project files created by IntelliJ IDEA *.iml *.ipr *.iws .idea ================================================ FILE: README.md ================================================ spring-data-elasticsearch-sample-application ============================================ Spring Data Elasticsearch Sample Application ================================================ FILE: pom.xml ================================================ 4.0.0 spring-data-elasticsearch-sample-application spring-data-elasticsearch-sample-application 1.0-SNAPSHOT 4.11 4.0.0.RELEASE default true spring-milestone Spring Maven Milestone Repository http://repo.springsource.org/libs-milestone com.springsource.repository.maven.snapshot http://maven.springframework.org/snapshot/ true com.springsource.repository.bundles.release http://repository.springsource.com/maven/bundles/release central Central Repository http://repo.maven.apache.org/maven2 default false never The Apache Software License, Version 2.0 http://www.apache.org/licenses/LICENSE-2.0.txt repo Copyright 2013 the original author or authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. org.springframework.data spring-data-elasticsearch 1.2.0.RELEASE org.springframework spring-context ${spring.version} commons-logging commons-logging org.springframework spring-test ${spring.version} test junit junit ${junit.version} test commons-logging commons-logging 1.1.1 ================================================ FILE: src/main/java/org/springframework/data/elasticsearch/entities/Article.java ================================================ package org.springframework.data.elasticsearch.entities; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.MultiField; import org.springframework.data.elasticsearch.annotations.NestedField; import java.util.ArrayList; import java.util.Collection; import java.util.List; import static org.springframework.data.elasticsearch.annotations.FieldIndex.analyzed; import static org.springframework.data.elasticsearch.annotations.FieldIndex.not_analyzed; import static org.springframework.data.elasticsearch.annotations.FieldType.Integer; import static org.springframework.data.elasticsearch.annotations.FieldType.String; @Document(indexName = "articles", type = "article", shards = 1, replicas = 0, refreshInterval = "-1", indexStoreType = "memory") public class Article { @Id private String id; private String title; @MultiField( mainField = @Field(type = String, index = analyzed), otherFields = { @NestedField(dotSuffix = "untouched", type = String, store = true, index = not_analyzed), @NestedField(dotSuffix = "sort", type = String, store = true, indexAnalyzer = "keyword") } ) private List authors = new ArrayList(); @Field(type = Integer, store = true) private List publishedYears = new ArrayList(); @Field(type = String, store = true) private Collection tags = new ArrayList(); private int score; public Article() { } public Article(String id) { this.id = id; } public void setId(String id) { this.id = id; } public String getId() { return id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public List getAuthors() { return authors; } public void setAuthors(List authors) { this.authors = authors; } public List getPublishedYears() { return publishedYears; } public void setPublishedYears(List publishedYears) { this.publishedYears = publishedYears; } public int getScore() { return score; } public void setScore(int score) { this.score = score; } public Collection getTags() { return tags; } public void setTags(Collection tags) { this.tags = tags; } } ================================================ FILE: src/main/java/org/springframework/data/elasticsearch/entities/ArticleBuilder.java ================================================ package org.springframework.data.elasticsearch.entities; import org.springframework.data.elasticsearch.core.query.IndexQuery; import java.util.ArrayList; import java.util.List; public class ArticleBuilder { private Article result; public ArticleBuilder(String id) { result = new Article(id); } public ArticleBuilder title(String title) { result.setTitle(title); return this; } public ArticleBuilder addAuthor(String author) { result.getAuthors().add(author); return this; } public ArticleBuilder addPublishedYear(Integer year) { result.getPublishedYears().add(year); return this; } public ArticleBuilder score(int score) { result.setScore(score); return this; } public Article build() { return result; } public ArticleBuilder addTag(String tag) { List tagsTmp = new ArrayList(); if(result.getTags()==null){ result.setTags(tagsTmp); }else { tagsTmp = (List) result.getTags(); } tagsTmp.add(tag); return this; } public IndexQuery buildIndex() { IndexQuery indexQuery = new IndexQuery(); indexQuery.setId(result.getId()); indexQuery.setObject(result); return indexQuery; } } ================================================ FILE: src/main/java/org/springframework/data/elasticsearch/entities/Author.java ================================================ /* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.elasticsearch.entities; /** * @author Rizwan Idrees * @author Mohsin Husen */ public class Author { private String id; private String name; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } ================================================ FILE: src/main/java/org/springframework/data/elasticsearch/entities/Book.java ================================================ package org.springframework.data.elasticsearch.entities; import java.util.Collection; import java.util.HashMap; import java.util.Map; import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Version; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; @Document(indexName = "book",type = "book" , shards = 1, replicas = 0, indexStoreType = "memory", refreshInterval = "-1") public class Book { @Id private String id; private String name; private Long price; @Version private Long version; public Map> getBuckets() { return buckets; } public void setBuckets(Map> buckets) { this.buckets = buckets; } @Field(type = FieldType.Nested) private Map> buckets = new HashMap(); public Book(){} public Book(String id, String name,Long version) { this.id = id; this.name = name; this.version = version; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Long getPrice() { return price; } public void setPrice(Long price) { this.price = price; } public long getVersion() { return version; } public void setVersion(long version) { this.version = version; } } ================================================ FILE: src/main/java/org/springframework/data/elasticsearch/entities/Car.java ================================================ /* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.elasticsearch.entities; /** * @author Rizwan Idrees * @author Mohsin Husen * @author Artur Konczak */ public class Car { private String name; private String model; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getModel() { return model; } public void setModel(String model) { this.model = model; } } ================================================ FILE: src/main/java/org/springframework/data/elasticsearch/entities/GirlFriend.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.elasticsearch.entities; import java.util.List; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; /** * @author Mohsin Husen */ public class GirlFriend { private String name; private String type; @Field(type = FieldType.Nested) private List cars; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() { return type; } public void setType(String type) { this.type = type; } public List getCars() { return cars; } public void setCars(List cars) { this.cars = cars; } } ================================================ FILE: src/main/java/org/springframework/data/elasticsearch/entities/OperationDocument.java ================================================ package org.springframework.data.elasticsearch.entities; import java.util.Date; import java.util.List; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.*; /** * Created by mohsinhusen on 10/04/15. */ @Document(indexName = "operations", type = "operation") public class OperationDocument { @Id private Long id; @Field( type = FieldType.String, index = FieldIndex.analyzed, searchAnalyzer = "standard", indexAnalyzer = "standard", store = true ) private String operationName; @Field( type = FieldType.Date, index = FieldIndex.not_analyzed, store = true, format = DateFormat.custom, pattern = "dd.MM.yyyy hh:mm" ) private Date dateUp; @Field( type = FieldType.String, index = FieldIndex.not_analyzed, store = false ) private String someTransientData; @Field(type = FieldType.Nested) private List sectors; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getOperationName() { return operationName; } public void setOperationName(String operationName) { this.operationName = operationName; } public Date getDateUp() { return dateUp; } public void setDateUp(Date dateUp) { this.dateUp = dateUp; } public String getSomeTransientData() { return someTransientData; } public void setSomeTransientData(String someTransientData) { this.someTransientData = someTransientData; } public List getSectors() { return sectors; } public void setSectors(List sectors) { this.sectors = sectors; } } ================================================ FILE: src/main/java/org/springframework/data/elasticsearch/entities/Person.java ================================================ /* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.elasticsearch.entities; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; import java.util.List; /** * @author Rizwan Idrees * @author Mohsin Husen * @author Artur Konczak */ @Document( indexName = "person" , type = "user", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") public class Person { @Id private String id; private String name; @Field( type = FieldType.Nested) private List car; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List getCar() { return car; } public void setCar(List car) { this.car = car; } } ================================================ FILE: src/main/java/org/springframework/data/elasticsearch/entities/PersonMultipleLevelNested.java ================================================ /* * Copyright 2014 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.elasticsearch.entities; import java.util.List; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; /** * @author Rizwan Idrees * @author Mohsin Husen * @author Artur Konczak */ @Document(indexName = "person-multiple-level-nested", type = "user", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1") public class PersonMultipleLevelNested { @Id private String id; private String name; @Field(type = FieldType.Nested) private List girlFriends; @Field(type = FieldType.Nested) private List cars; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List getGirlFriends() { return girlFriends; } public void setGirlFriends(List girlFriends) { this.girlFriends = girlFriends; } public List getCars() { return cars; } public void setCars(List cars) { this.cars = cars; } } ================================================ FILE: src/main/java/org/springframework/data/elasticsearch/entities/Product.java ================================================ package org.springframework.data.elasticsearch.entities; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; @Document(indexName = "book",type = "book" , shards = 1, replicas = 0, indexStoreType = "memory", refreshInterval = "-1") public class Product { @Id private String id; private String name; private String description; private boolean enabled; public Product() { } public Product(String id, String name, String description, boolean enabled) { this(); this.id = id; this.name = name; this.description = description; this.enabled = enabled; } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } } ================================================ FILE: src/main/java/org/springframework/data/elasticsearch/entities/Sector.java ================================================ package org.springframework.data.elasticsearch.entities; /** * Created by mohsinhusen on 10/04/15. */ public class Sector { private int id; private String sectorName; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getSectorName() { return sectorName; } public void setSectorName(String sectorName) { this.sectorName = sectorName; } } ================================================ FILE: src/main/java/org/springframework/data/elasticsearch/repositories/OperationDocumentRepository.java ================================================ package org.springframework.data.elasticsearch.repositories; import org.springframework.data.elasticsearch.entities.OperationDocument; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; /** * Created by mohsinhusen on 10/04/15. */ public interface OperationDocumentRepository extends ElasticsearchRepository { } ================================================ FILE: src/main/java/org/springframework/data/elasticsearch/repositories/SampleArticleRepository.java ================================================ package org.springframework.data.elasticsearch.repositories; import org.springframework.data.elasticsearch.entities.Article; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; public interface SampleArticleRepository extends ElasticsearchRepository { } ================================================ FILE: src/main/java/org/springframework/data/elasticsearch/repositories/SampleProductRepository.java ================================================ package org.springframework.data.elasticsearch.repositories; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.entities.Product; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import java.util.List; public interface SampleProductRepository extends ElasticsearchRepository { List findByName(String name); List findByName(String name, Pageable pageable); List findByNameAndId(String name, String id); } ================================================ FILE: src/main/java/org/springframework/data/elasticsearch/repositories/book/SampleBookRepository.java ================================================ package org.springframework.data.elasticsearch.repositories.book; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.entities.Book; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; public interface SampleBookRepository extends ElasticsearchRepository { Page findByNameAndPrice(String name, Integer price, Pageable pageable); Page findByNameOrPrice(String name, Integer price, Pageable pageable); Page findByName(String name, Pageable pageable); } ================================================ FILE: src/test/java/org/springframework/data/elasticsearch/ComplexNestedTypeContactTests.java ================================================ package org.springframework.data.elasticsearch; import static org.elasticsearch.index.query.QueryBuilders.*; import static org.hamcrest.core.Is.is; import java.util.Arrays; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.query.*; import org.springframework.data.elasticsearch.entities.Contact; import org.springframework.data.elasticsearch.entities.Manuscript; import org.springframework.data.elasticsearch.entities.Role; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; /** * Created by huse01 on 31/03/14. */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:/contact-test.xml") public class ComplexNestedTypeContactTests { @Autowired private ElasticsearchTemplate template; @Before public void before() { template.deleteIndex(Contact.class); template.createIndex(Contact.class); template.putMapping(Contact.class); } @Test public void test() { Contact contact1 = new Contact(); contact1.setId("1"); contact1.setName("2"); Manuscript manuscript1 = new Manuscript(); manuscript1.setTitle("t1"); manuscript1.setAbstractText("t2"); manuscript1.setStatus("ACCEPTED"); Role role1 = new Role(); role1.setName("role1"); Role role2 = new Role(); role2.setName("role2"); manuscript1.setRole(Arrays.asList(role1, role2)); Manuscript manuscript2 = new Manuscript(); manuscript2.setTitle("t1"); manuscript2.setAbstractText("t2"); manuscript2.setStatus("DELETED"); Role role3 = new Role(); role3.setName("role3"); manuscript2.setRole(Arrays.asList(role3)); contact1.setManuscripts(Arrays.asList(manuscript1,manuscript2)); IndexQuery indexQuery = new IndexQueryBuilder().withObject(contact1) .withIndexName("test-contact-test").withId(contact1.getId()) .withType("contact-test-type").build(); template.bulkIndex(Arrays.asList(indexQuery)); template.refresh("test-contact-test", true); BoolQueryBuilder builder = boolQuery(); builder.must(nestedQuery("manuscripts", termQuery("manuscripts.status", "ACCEPTED"))) .must(nestedQuery("manuscripts.role", termQuery("manuscripts.role.name", "role3"))); SearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(builder).build(); Page page = template.queryForPage(searchQuery, Contact.class); Assert.assertThat(page.getTotalElements(), is(1L)); } } ================================================ FILE: src/test/java/org/springframework/data/elasticsearch/entities/Contact.java ================================================ package org.springframework.data.elasticsearch.entities; import java.util.List; import java.util.Set; import org.springframework.data.annotation.Id; import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldType; /** * Created by huse01 on 31/03/14. */ @Document(indexName = "test-contact-test",type = "contact-test-type", shards = 1, replicas = 0) public class Contact { @Id private String id; private String name; @Field(type = FieldType.Nested) private List manuscripts; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List getManuscripts() { return manuscripts; } public void setManuscripts(List manuscripts) { this.manuscripts = manuscripts; } } ================================================ FILE: src/test/java/org/springframework/data/elasticsearch/entities/Manuscript.java ================================================ package org.springframework.data.elasticsearch.entities; import java.util.List; import java.util.Set; import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.FieldIndex; import org.springframework.data.elasticsearch.annotations.FieldType; /** * Created by huse01 on 31/03/14. */ public class Manuscript { private String title; private String abstractText; @Field(type = FieldType.String, index = FieldIndex.not_analyzed) private String status; @Field(type = FieldType.Nested) private List role; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getAbstractText() { return abstractText; } public void setAbstractText(String abstractText) { this.abstractText = abstractText; } public List getRole() { return role; } public void setRole(List role) { this.role = role; } } ================================================ FILE: src/test/java/org/springframework/data/elasticsearch/entities/Role.java ================================================ package org.springframework.data.elasticsearch.entities; /** * Created by huse01 on 31/03/14. */ public class Role { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } } ================================================ FILE: src/test/java/org/springframework/data/elasticsearch/repositories/ElasticsearchFacetTests.java ================================================ package org.springframework.data.elasticsearch.repositories; import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.search.facet.FacetBuilders; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.FacetedPage; import org.springframework.data.elasticsearch.core.facet.request.NativeFacetRequest; import org.springframework.data.elasticsearch.core.facet.request.RangeFacetRequestBuilder; import org.springframework.data.elasticsearch.core.facet.request.TermFacetRequestBuilder; import org.springframework.data.elasticsearch.core.facet.result.Range; import org.springframework.data.elasticsearch.core.facet.result.RangeResult; import org.springframework.data.elasticsearch.core.facet.result.Term; import org.springframework.data.elasticsearch.core.facet.result.TermResult; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.data.elasticsearch.entities.Article; import org.springframework.data.elasticsearch.entities.ArticleBuilder; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsEqual.equalTo; import static org.hamcrest.core.IsNull.nullValue; import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:/springContext-test.xml") public class ElasticsearchFacetTests { public static final String RIZWAN_IDREES = "Rizwan Idrees"; public static final String MOHSIN_HUSEN = "Mohsin Husen"; public static final String JONATHAN_YAN = "Jonathan Yan"; public static final String ARTUR_KONCZAK = "Artur Konczak"; public static final int YEAR_2002 = 2002; public static final int YEAR_2001 = 2001; public static final int YEAR_2000 = 2000; @Autowired private ElasticsearchTemplate elasticsearchTemplate; @Before public void before() { elasticsearchTemplate.deleteIndex(Article.class); elasticsearchTemplate.createIndex(Article.class); elasticsearchTemplate.putMapping(Article.class); elasticsearchTemplate.refresh(Article.class, true); IndexQuery article1 = new ArticleBuilder("1").title("article four").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addAuthor(JONATHAN_YAN).score(10).buildIndex(); IndexQuery article2 = new ArticleBuilder("2").title("article three").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addAuthor(MOHSIN_HUSEN).addPublishedYear(YEAR_2000).score(20).buildIndex(); IndexQuery article3 = new ArticleBuilder("3").title("article two").addAuthor(RIZWAN_IDREES).addAuthor(ARTUR_KONCZAK).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(30).buildIndex(); IndexQuery article4 = new ArticleBuilder("4").title("article one").addAuthor(RIZWAN_IDREES).addPublishedYear(YEAR_2002).addPublishedYear(YEAR_2001).addPublishedYear(YEAR_2000).score(40).buildIndex(); elasticsearchTemplate.index(article1); elasticsearchTemplate.index(article2); elasticsearchTemplate.index(article3); elasticsearchTemplate.index(article4); elasticsearchTemplate.refresh(Article.class, true); } @Test public void shouldReturnFacetedAuthorsForGivenQueryWithDefaultOrder() { String facetName = "fauthors"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withFacet(new TermFacetRequestBuilder(facetName).fields("authors.untouched").build()).build(); // when FacetedPage
result = elasticsearchTemplate.queryForPage(searchQuery, Article.class); // then assertThat(result.getNumberOfElements(), is(equalTo(4))); TermResult facet = (TermResult) result.getFacet(facetName); Term term = facet.getTerms().get(0); assertThat(term.getTerm(), is(RIZWAN_IDREES)); assertThat(term.getCount(), is(4)); term = facet.getTerms().get(1); assertThat(term.getTerm(), is(ARTUR_KONCZAK)); assertThat(term.getCount(), is(3)); term = facet.getTerms().get(2); assertThat(term.getTerm(), is(MOHSIN_HUSEN)); assertThat(term.getCount(), is(2)); term = facet.getTerms().get(3); assertThat(term.getTerm(), is(JONATHAN_YAN)); assertThat(term.getCount(), is(1)); } @Test public void shouldReturnFacetedAuthorsForGivenFilteredQuery() { // given String facetName = "fauthors"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFilter(FilterBuilders.notFilter(FilterBuilders.termFilter("title", "four"))) .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").build()).build(); // when FacetedPage
result = elasticsearchTemplate.queryForPage(searchQuery, Article.class); // then assertThat(result.getNumberOfElements(), is(equalTo(3))); TermResult facet = (TermResult) result.getFacet(facetName); Term term = facet.getTerms().get(0); assertThat(term.getTerm(), is(RIZWAN_IDREES)); assertThat(term.getCount(), is(3)); term = facet.getTerms().get(1); assertThat(term.getTerm(), is(ARTUR_KONCZAK)); assertThat(term.getCount(), is(2)); term = facet.getTerms().get(2); assertThat(term.getTerm(), is(MOHSIN_HUSEN)); assertThat(term.getCount(), is(1)); } @Test public void shouldExcludeTermsFromFacetedAuthorsForGivenQuery() { // given String facetName = "fauthors"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFilter(FilterBuilders.notFilter(FilterBuilders.termFilter("title", "four"))) .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").excludeTerms(RIZWAN_IDREES, ARTUR_KONCZAK).build()).build(); // when FacetedPage
result = elasticsearchTemplate.queryForPage(searchQuery, Article.class); // then assertThat(result.getNumberOfElements(), is(equalTo(3))); TermResult facet = (TermResult) result.getFacet(facetName); assertThat(facet.getTerms().size(), is(1)); Term term = facet.getTerms().get(0); assertThat(term.getTerm(), is(MOHSIN_HUSEN)); assertThat(term.getCount(), is(1)); } @Test public void shouldReturnFacetedAuthorsForGivenQueryOrderedByTerm() { // given String facetName = "fauthors"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFacet(new TermFacetRequestBuilder(facetName).fields("authors.untouched").ascTerm().build()).build(); // when FacetedPage
result = elasticsearchTemplate.queryForPage(searchQuery, Article.class); // then assertThat(result.getNumberOfElements(), is(equalTo(4))); TermResult facet = (TermResult) result.getFacet(facetName); Term term = facet.getTerms().get(0); assertThat(term.getTerm(), is(ARTUR_KONCZAK)); assertThat(term.getCount(), is(3)); term = facet.getTerms().get(1); assertThat(term.getTerm(), is(JONATHAN_YAN)); assertThat(term.getCount(), is(1)); term = facet.getTerms().get(2); assertThat(term.getTerm(), is(MOHSIN_HUSEN)); assertThat(term.getCount(), is(2)); term = facet.getTerms().get(3); assertThat(term.getTerm(), is(RIZWAN_IDREES)); assertThat(term.getCount(), is(4)); } @Test public void shouldReturnFacetedAuthorsForGivenQueryOrderedByCountAsc() { // given String facetName = "fauthors"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFacet(new TermFacetRequestBuilder(facetName).fields("authors.untouched").ascCount().build()).build(); // when FacetedPage
result = elasticsearchTemplate.queryForPage(searchQuery, Article.class); // then assertThat(result.getNumberOfElements(), is(equalTo(4))); TermResult facet = (TermResult) result.getFacet(facetName); Term term = facet.getTerms().get(0); assertThat(term.getTerm(), is(JONATHAN_YAN)); assertThat(term.getCount(), is(1)); term = facet.getTerms().get(1); assertThat(term.getTerm(), is(MOHSIN_HUSEN)); assertThat(term.getCount(), is(2)); term = facet.getTerms().get(2); assertThat(term.getTerm(), is(ARTUR_KONCZAK)); assertThat(term.getCount(), is(3)); term = facet.getTerms().get(3); assertThat(term.getTerm(), is(RIZWAN_IDREES)); assertThat(term.getCount(), is(4)); } @Test public void shouldReturnFacetedYearsForGivenQuery() { // given String facetName = "fyears"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFacet(new TermFacetRequestBuilder(facetName).fields("publishedYears").descCount().build()).build(); // when FacetedPage
result = elasticsearchTemplate.queryForPage(searchQuery, Article.class); // then assertThat(result.getNumberOfElements(), is(equalTo(4))); TermResult facet = (TermResult) result.getFacet(facetName); assertThat(facet.getTerms().size(), is(equalTo(3))); Term term = facet.getTerms().get(0); assertThat(term.getTerm(), is(Integer.toString(YEAR_2000))); assertThat(term.getCount(), is(3)); term = facet.getTerms().get(1); assertThat(term.getTerm(), is(Integer.toString(YEAR_2001))); assertThat(term.getCount(), is(2)); term = facet.getTerms().get(2); assertThat(term.getTerm(), is(Integer.toString(YEAR_2002))); assertThat(term.getCount(), is(1)); } @Test public void shouldReturnSingleFacetOverYearsAndAuthorsForGivenQuery() { // given String facetName = "fyears"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFacet(new TermFacetRequestBuilder(facetName).fields("publishedYears", "authors.untouched").ascTerm().build()).build(); // when FacetedPage
result = elasticsearchTemplate.queryForPage(searchQuery, Article.class); // then assertThat(result.getNumberOfElements(), is(equalTo(4))); TermResult facet = (TermResult) result.getFacet(facetName); assertThat(facet.getTerms().size(), is(equalTo(7))); Term term = facet.getTerms().get(0); assertThat(term.getTerm(), is(Integer.toString(YEAR_2000))); assertThat(term.getCount(), is(3)); term = facet.getTerms().get(1); assertThat(term.getTerm(), is(Integer.toString(YEAR_2001))); assertThat(term.getCount(), is(2)); term = facet.getTerms().get(2); assertThat(term.getTerm(), is(Integer.toString(YEAR_2002))); assertThat(term.getCount(), is(1)); term = facet.getTerms().get(3); assertThat(term.getTerm(), is(ARTUR_KONCZAK)); assertThat(term.getCount(), is(3)); term = facet.getTerms().get(4); assertThat(term.getTerm(), is(JONATHAN_YAN)); assertThat(term.getCount(), is(1)); term = facet.getTerms().get(5); assertThat(term.getTerm(), is(MOHSIN_HUSEN)); assertThat(term.getCount(), is(2)); term = facet.getTerms().get(6); assertThat(term.getTerm(), is(RIZWAN_IDREES)); assertThat(term.getCount(), is(4)); } @Test public void shouldReturnFacetedYearsAndFacetedAuthorsForGivenQuery() { // given String numberFacetName = "fAuthors"; String stringFacetName = "fyears"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFacet(new TermFacetRequestBuilder(numberFacetName).fields("publishedYears").ascTerm().build()) .withFacet(new TermFacetRequestBuilder(stringFacetName).fields("authors.untouched").ascTerm().build()) .build(); // when FacetedPage
result = elasticsearchTemplate.queryForPage(searchQuery, Article.class); // then assertThat(result.getNumberOfElements(), is(equalTo(4))); TermResult numberFacet = (TermResult) result.getFacet(numberFacetName); assertThat(numberFacet.getTerms().size(), is(equalTo(3))); Term numberTerm = numberFacet.getTerms().get(0); assertThat(numberTerm.getTerm(), is(Integer.toString(YEAR_2000))); assertThat(numberTerm.getCount(), is(3)); numberTerm = numberFacet.getTerms().get(1); assertThat(numberTerm.getTerm(), is(Integer.toString(YEAR_2001))); assertThat(numberTerm.getCount(), is(2)); numberTerm = numberFacet.getTerms().get(2); assertThat(numberTerm.getTerm(), is(Integer.toString(YEAR_2002))); assertThat(numberTerm.getCount(), is(1)); TermResult stringFacet = (TermResult) result.getFacet(stringFacetName); Term stringTerm = stringFacet.getTerms().get(0); assertThat(stringTerm.getTerm(), is(ARTUR_KONCZAK)); assertThat(stringTerm.getCount(), is(3)); stringTerm = stringFacet.getTerms().get(1); assertThat(stringTerm.getTerm(), is(JONATHAN_YAN)); assertThat(stringTerm.getCount(), is(1)); stringTerm = stringFacet.getTerms().get(2); assertThat(stringTerm.getTerm(), is(MOHSIN_HUSEN)); assertThat(stringTerm.getCount(), is(2)); stringTerm = stringFacet.getTerms().get(3); assertThat(stringTerm.getTerm(), is(RIZWAN_IDREES)); assertThat(stringTerm.getCount(), is(4)); } @Test public void shouldReturnFacetedYearsForNativeFacet() { // given String facetName = "fyears"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFacet(new NativeFacetRequest(FacetBuilders.termsFacet(facetName).field("publishedYears"))).build(); // when FacetedPage
result = elasticsearchTemplate.queryForPage(searchQuery, Article.class); // then assertThat(result.getNumberOfElements(), is(equalTo(4))); TermResult facet = (TermResult) result.getFacet(facetName); assertThat(facet.getTerms().size(), is(equalTo(3))); Term term = facet.getTerms().get(0); assertThat(term.getTerm(), is(Integer.toString(YEAR_2000))); assertThat(term.getCount(), is(3)); term = facet.getTerms().get(1); assertThat(term.getTerm(), is(Integer.toString(YEAR_2001))); assertThat(term.getCount(), is(2)); term = facet.getTerms().get(2); assertThat(term.getTerm(), is(Integer.toString(YEAR_2002))); assertThat(term.getCount(), is(1)); } @Test public void shouldFilterResultByRegexForGivenQuery() { // given String facetName = "regex_authors"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFilter(FilterBuilders.notFilter(FilterBuilders.termFilter("title", "four"))) .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").regex("Art.*").build()).build(); // when FacetedPage
result = elasticsearchTemplate.queryForPage(searchQuery, Article.class); // then assertThat(result.getNumberOfElements(), is(equalTo(3))); TermResult facet = (TermResult) result.getFacet(facetName); assertThat(facet.getTerms().size(), is(1)); Term term = facet.getTerms().get(0); assertThat(term.getTerm(), is(ARTUR_KONCZAK)); assertThat(term.getCount(), is(2)); } @Test public void shouldReturnAllTermsForGivenQuery() { // given String facetName = "all_authors"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFilter(FilterBuilders.notFilter(FilterBuilders.termFilter("title", "four"))) .withFacet(new TermFacetRequestBuilder(facetName).applyQueryFilter().fields("authors.untouched").allTerms().build()).build(); // when FacetedPage
result = elasticsearchTemplate.queryForPage(searchQuery, Article.class); // then assertThat(result.getNumberOfElements(), is(equalTo(3))); TermResult facet = (TermResult) result.getFacet(facetName); assertThat(facet.getTerms().size(), is(4)); } @Test public void shouldReturnRangeFacetForGivenQuery() { // given String facetName = "rangeYears"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFacet( new RangeFacetRequestBuilder(facetName).field("publishedYears") .to(YEAR_2000).range(YEAR_2000, YEAR_2002).from(YEAR_2002).build() ).build(); // when FacetedPage
result = elasticsearchTemplate.queryForPage(searchQuery, Article.class); // then assertThat(result.getNumberOfElements(), is(equalTo(4))); RangeResult facet = (RangeResult) result.getFacet(facetName); assertThat(facet.getRanges().size(), is(equalTo(3))); Range range = facet.getRanges().get(0); assertThat(range.getFrom(), nullValue()); assertThat(range.getTo(), is((double) YEAR_2000)); assertThat(range.getCount(), is(0L)); assertThat(range.getTotal(), is(0.0)); range = facet.getRanges().get(1); assertThat(range.getFrom(), is((double) YEAR_2000)); assertThat(range.getTo(), is((double) YEAR_2002)); assertThat(range.getCount(), is(3L)); assertThat(range.getTotal(), is(6000.0)); range = facet.getRanges().get(2); assertThat(range.getFrom(), is((double) YEAR_2002)); assertThat(range.getTo(), nullValue()); assertThat(range.getCount(), is(1L)); assertThat(range.getTotal(), is(2002.0)); } @Test public void shouldReturnKeyValueRangeFacetForGivenQuery() { // given String facetName = "rangeScoreOverYears"; SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()) .withFacet( new RangeFacetRequestBuilder(facetName).fields("publishedYears", "score") .to(YEAR_2000).range(YEAR_2000, YEAR_2002).from(YEAR_2002).build() ).build(); // when FacetedPage
result = elasticsearchTemplate.queryForPage(searchQuery, Article.class); // then assertThat(result.getNumberOfElements(), is(equalTo(4))); RangeResult facet = (RangeResult) result.getFacet(facetName); assertThat(facet.getRanges().size(), is(equalTo(3))); Range range = facet.getRanges().get(0); assertThat(range.getFrom(), nullValue()); assertThat(range.getTo(), is((double) YEAR_2000)); assertThat(range.getCount(), is(0L)); assertThat(range.getTotal(), is(0.0)); range = facet.getRanges().get(1); assertThat(range.getFrom(), is((double) YEAR_2000)); assertThat(range.getTo(), is((double) YEAR_2002)); assertThat(range.getCount(), is(3L)); assertThat(range.getTotal(), is(90.0)); range = facet.getRanges().get(2); assertThat(range.getFrom(), is((double) YEAR_2002)); assertThat(range.getTo(), nullValue()); assertThat(range.getCount(), is(1L)); assertThat(range.getTotal(), is(40.0)); } } ================================================ FILE: src/test/java/org/springframework/data/elasticsearch/repositories/NestedObjectTests.java ================================================ /* * Copyright 2013 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.data.elasticsearch.repositories; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.QueryBuilder; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.query.GetQuery; import org.springframework.data.elasticsearch.core.query.IndexQuery; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.data.elasticsearch.entities.*; import org.springframework.data.elasticsearch.repositories.book.SampleBookRepository; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric; import static org.elasticsearch.index.query.QueryBuilders.boolQuery; import static org.elasticsearch.index.query.QueryBuilders.nestedQuery; import static org.elasticsearch.index.query.QueryBuilders.termQuery; import static org.hamcrest.core.Is.is; import static org.hamcrest.core.IsNull.notNullValue; import static org.junit.Assert.assertThat; /** * @author Rizwan Idrees * @author Mohsin Husen * @author Artur Konczak */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:/springContext-test.xml") public class NestedObjectTests { @Autowired private ElasticsearchTemplate elasticsearchTemplate; @Autowired private SampleBookRepository bookRepository; @Before public void before() { elasticsearchTemplate.deleteIndex(Book.class); elasticsearchTemplate.createIndex(Book.class); elasticsearchTemplate.refresh(Book.class, true); elasticsearchTemplate.deleteIndex(Person.class); elasticsearchTemplate.createIndex(Person.class); elasticsearchTemplate.putMapping(Person.class); elasticsearchTemplate.refresh(Person.class, true); elasticsearchTemplate.deleteIndex(PersonMultipleLevelNested.class); elasticsearchTemplate.createIndex(PersonMultipleLevelNested.class); elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class); elasticsearchTemplate.refresh(PersonMultipleLevelNested.class, true); } @Test public void shouldIndexInnerObject() { // given String id = randomAlphanumeric(5); Book book = new Book(); book.setId(id); book.setName("xyz"); book.setVersion(System.nanoTime()); Author author = new Author(); author.setId("1"); author.setName("ABC"); // when bookRepository.save(book); // then assertThat(bookRepository.findOne(id), is(notNullValue())); } @Test public void shouldIndexInitialLevelNestedObject(){ List cars = new ArrayList(); Car saturn = new Car(); saturn.setName("Saturn"); saturn.setModel("SL"); Car subaru = new Car(); subaru.setName("Subaru"); subaru.setModel("Imprezza"); Car ford = new Car(); ford.setName("Ford"); ford.setModel("Focus"); cars.add(saturn); cars.add(subaru); cars.add(ford); Person foo = new Person(); foo.setName("Foo"); foo.setId("1"); foo.setCar(cars); Car car = new Car(); car.setName("Saturn"); car.setModel("Imprezza"); Person bar = new Person(); bar.setId("2"); bar.setName("Bar"); bar.setCar(Arrays.asList(car)); List indexQueries = new ArrayList(); IndexQuery indexQuery1 = new IndexQuery(); indexQuery1.setId(foo.getId()); indexQuery1.setObject(foo); IndexQuery indexQuery2 = new IndexQuery(); indexQuery2.setId(bar.getId()); indexQuery2.setObject(bar); indexQueries.add(indexQuery1); indexQueries.add(indexQuery2); elasticsearchTemplate.putMapping(Person.class); elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(Person.class, true); QueryBuilder builder = nestedQuery("car", boolQuery().must(termQuery("car.name", "saturn")).must(termQuery("car.model", "imprezza"))); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(builder).build(); List persons = elasticsearchTemplate.queryForList(searchQuery, Person.class); assertThat(persons.size() , is(1)); } @Test public void shouldIndexMultipleLevelNestedObject() { //given List indexQueries = createPerson(); //when elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class); elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(PersonMultipleLevelNested.class, true); //then GetQuery getQuery = new GetQuery(); getQuery.setId("1"); PersonMultipleLevelNested personIndexed = elasticsearchTemplate.queryForObject(getQuery, PersonMultipleLevelNested.class); assertThat(personIndexed, is(notNullValue())); } @Test public void shouldSearchUsingNestedQueryOnMultipleLevelNestedObject() { //given List indexQueries = createPerson(); //when elasticsearchTemplate.putMapping(PersonMultipleLevelNested.class); elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.refresh(PersonMultipleLevelNested.class, true); //then BoolQueryBuilder builder = boolQuery(); builder.must(nestedQuery("girlFriends", termQuery("girlFriends.type", "temp"))) .must(nestedQuery("girlFriends.cars", termQuery("girlFriends.cars.name", "Ford".toLowerCase()))); SearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(builder) .build(); Page personIndexed = elasticsearchTemplate.queryForPage(searchQuery, PersonMultipleLevelNested.class); assertThat(personIndexed, is(notNullValue())); assertThat(personIndexed.getTotalElements(), is(1L)); assertThat(personIndexed.getContent().get(0).getId(), is("1")); } private List createPerson() { PersonMultipleLevelNested person1 = new PersonMultipleLevelNested(); person1.setId("1"); person1.setName("name"); Car saturn = new Car(); saturn.setName("Saturn"); saturn.setModel("SL"); Car subaru = new Car(); subaru.setName("Subaru"); subaru.setModel("Imprezza"); Car car = new Car(); car.setName("Saturn"); car.setModel("Imprezza"); Car ford = new Car(); ford.setName("Ford"); ford.setModel("Focus"); GirlFriend permanent = new GirlFriend(); permanent.setName("permanent"); permanent.setType("permanent"); permanent.setCars(Arrays.asList(saturn, subaru)); GirlFriend temp = new GirlFriend(); temp.setName("temp"); temp.setType("temp"); temp.setCars(Arrays.asList(car, ford)); person1.setGirlFriends(Arrays.asList(permanent, temp)); IndexQuery indexQuery1 = new IndexQuery(); indexQuery1.setId(person1.getId()); indexQuery1.setObject(person1); PersonMultipleLevelNested person2 = new PersonMultipleLevelNested(); person2.setId("2"); person2.setName("name"); person2.setGirlFriends(Arrays.asList(permanent)); IndexQuery indexQuery2 = new IndexQuery(); indexQuery2.setId(person2.getId()); indexQuery2.setObject(person2); List indexQueries = new ArrayList(); indexQueries.add(indexQuery1); indexQueries.add(indexQuery2); return indexQueries; } } ================================================ FILE: src/test/java/org/springframework/data/elasticsearch/repositories/OperationDocumentRepositoryTest.java ================================================ package org.springframework.data.elasticsearch.repositories; import java.util.Map; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.entities.OperationDocument; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:/spring-context.xml") public class OperationDocumentRepositoryTest { @Autowired private ElasticsearchTemplate elasticsearchTemplate; @Autowired private OperationDocumentRepository repository; @Test public void test() { Map mapping = elasticsearchTemplate.getMapping(OperationDocument.class); System.out.println(mapping.toString()); } } ================================================ FILE: src/test/java/org/springframework/data/elasticsearch/repositories/SampleArticleRepositoryTest.java ================================================ package org.springframework.data.elasticsearch.repositories; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.data.elasticsearch.entities.Article; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import java.util.ArrayList; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:/springContext-test.xml") public class SampleArticleRepositoryTest { @Resource private SampleArticleRepository sampleArticleRepository; @Before public void emptyData(){ sampleArticleRepository.deleteAll(); } @Test public void shouldIndexSingleBookEntity(){ Article article = new Article(); article.setId("123455"); article.setTitle("Spring Data Elasticsearch Test Article"); List authors = new ArrayList(); authors.add("Author1"); authors.add("Author2"); article.setAuthors(authors); List tags = new ArrayList(); tags.add("tag1"); tags.add("tag2"); tags.add("tag3"); article.setTags(tags); //Indexing using sampleArticleRepository sampleArticleRepository.save(article); //lets try to search same record in elasticsearch Article indexedArticle = sampleArticleRepository.findOne(article.getId()); assertThat(indexedArticle,is(notNullValue())); assertThat(indexedArticle.getId(),is(article.getId())); assertThat(indexedArticle.getAuthors().size(),is(authors.size())); assertThat(indexedArticle.getTags().size(),is(tags.size())); } } ================================================ FILE: src/test/java/org/springframework/data/elasticsearch/repositories/SampleBookRepositoryTest.java ================================================ package org.springframework.data.elasticsearch.repositories; import org.apache.commons.lang.RandomStringUtils; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; import org.springframework.data.elasticsearch.core.ElasticsearchTemplate; import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder; import org.springframework.data.elasticsearch.core.query.SearchQuery; import org.springframework.data.elasticsearch.entities.Book; import org.springframework.data.elasticsearch.repositories.book.SampleBookRepository; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import java.util.*; import static java.util.Arrays.asList; import static org.elasticsearch.index.query.FilterBuilders.*; import static org.elasticsearch.index.query.QueryBuilders.*; import static org.hamcrest.CoreMatchers.*; import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:/springContext-book-test.xml") public class SampleBookRepositoryTest { @Resource private SampleBookRepository repository; @Resource private ElasticsearchTemplate template; @Before public void emptyData(){ repository.deleteAll(); } @Test public void shouldIndexSingleBookEntity(){ Book book = new Book(); book.setId("123455"); book.setName("Spring Data Elasticsearch"); book.setVersion(System.currentTimeMillis()); repository.save(book); //lets try to search same record in elasticsearch Book indexedBook = repository.findOne(book.getId()); assertThat(indexedBook,is(notNullValue())); assertThat(indexedBook.getId(),is(book.getId())); } @Test public void shouldBulkIndexMultipleBookEntities(){ Book book1 = new Book(RandomStringUtils.random(5),"Spring Data",System.currentTimeMillis()); Book book2 = new Book(RandomStringUtils.random(5),"Spring Data Elasticsearch",System.currentTimeMillis()); //Bulk Index using repository repository.save(asList(book1, book2)); //lets try to search same records in elasticsearch Book indexedBook1 = repository.findOne(book1.getId()); assertThat(indexedBook1.getId(), is(book1.getId())); Book indexedBook2 = repository.findOne(book2.getId()); assertThat(indexedBook2.getId(),is(book2.getId())); } @Test @Ignore("not to run as just for showing usage of repository ! might throw java.lang.OutOfMemoryError :-) ") public void crudRepositoryTest(){ Book book1 = new Book(RandomStringUtils.random(5),"Spring Data",System.currentTimeMillis()); Book book2 = new Book(RandomStringUtils.random(5),"Spring Data Elasticsearch",System.currentTimeMillis()); List books = Arrays.asList(book1,book2); //indexing single document repository.save(book1); //bulk indexing multiple documents repository.save(books); //searching single document based on documentId Book book = repository.findOne(book1.getId()); //to get all records as iteratable collection Iterable bookList = repository.findAll(); //page request which will give first 10 document Page bookPage = repository.findAll(new PageRequest(0,10)); // to get all records as ASC on name field Iterable bookIterable = repository.findAll(new Sort(new Sort.Order(Sort.Direction.ASC,"name"))); //to get total number of docoments in an index Long count = repository.count(); //to check wheather document exists or not boolean exists = repository.exists(book1.getId()); //delete a document by entity repository.delete(book1); //delete multiple document using collection repository.delete(books); //delete a document using documentId repository.delete(book1.getId()); //delete all document repository.deleteAll(); } @Test public void shouldCountAllElementsInIndex(){ List books = new ArrayList(); for(int i=1; i<=10 ; i++){ books.add(new Book(RandomStringUtils.random(5),"Spring Data Rocks !",System.currentTimeMillis())); } //Bulk Index using repository repository.save(books); //count all elements long count = repository.count(); assertThat(count,is(equalTo(10L))); } @Test public void shouldExecuteCustomSearchQueries(){ Book book1 = new Book(RandomStringUtils.random(5),"Custom Query",System.currentTimeMillis()); Book book2 = new Book(RandomStringUtils.random(5),null,System.currentTimeMillis()); //indexing a book repository.save(Arrays.asList(book1, book2)); SearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(matchAllQuery()) .withFilter(boolFilter().must(existsFilter("name"))) .withPageable(new PageRequest(0,10)) .build(); Page books = repository.search(searchQuery); assertThat(books.getNumberOfElements(), is(equalTo(1))); } /*@Test public void shouldExecuteCustomSearchQuery(){ Book book1 = new Book(RandomStringUtils.random(5),"Custom Query",System.currentTimeMillis()); Book book2 = new Book(RandomStringUtils.random(5),"Elasticsearch QueryBuilder",System.currentTimeMillis()); //bulk indexing two documents repository.save(Arrays.asList(book1, book2)); QueryBuilder queryBuilder = QueryBuilders.fieldQuery("name",book1.getName()); //searching in elasticsearch using repository Page search(QueryBuilder q, PageRequest p ) method. Page books = repository.search(queryBuilder,new PageRequest(0,20)); assertThat(books.getNumberOfElements(),is(equalTo(1))); }*/ @Test public void shouldReturnBooksForCustomMethodsWithAndCriteria(){ Book book1 = new Book(RandomStringUtils.random(5),"test",System.currentTimeMillis()); Book book2 = new Book(RandomStringUtils.random(5),"test",System.currentTimeMillis()); book1.setPrice(10L); book2.setPrice(10L); repository.save(Arrays.asList(book1, book2)); Page books = repository.findByNameAndPrice("test", 10, new PageRequest(0, 10)); assertThat(books.getContent().size(), is(2)); } @Test public void shouldReturnBooksWithName(){ Book book1 = new Book(RandomStringUtils.random(5),"test1",System.currentTimeMillis()); Book book2 = new Book(RandomStringUtils.random(5),"test2",System.currentTimeMillis()); repository.save(Arrays.asList(book1, book2)); Page books = repository.findByName("test1", new PageRequest(0, 10)); assertThat(books.getContent().size(), is(1)); } @Test public void shouldReturnBooksForGivenBucket(){ Book book1 = new Book(RandomStringUtils.random(5),"test1",System.currentTimeMillis()); Book book2 = new Book(RandomStringUtils.random(5),"test2",System.currentTimeMillis()); Map> map1 = new HashMap>(); map1.put(1, Arrays.asList("test1", "test2")); Map> map2 = new HashMap>(); map2.put(1, Arrays.asList("test3", "test4")); book1.setBuckets(map1); book2.setBuckets(map2); repository.save(Arrays.asList(book1,book2)); SearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(nestedQuery("buckets", termQuery("buckets.1", "test3"))) .build(); Page books = repository.search(searchQuery); assertThat(books.getContent().size(), is(1)); } @Test public void shouldReturnBooksForGivenBucketUsingTemplate(){ template.deleteIndex(Book.class); template.createIndex(Book.class); template.putMapping(Book.class); template.refresh(Book.class, true); Book book1 = new Book(RandomStringUtils.random(5),"test1",System.currentTimeMillis()); Book book2 = new Book(RandomStringUtils.random(5),"test2",System.currentTimeMillis()); Map> map1 = new HashMap>(); map1.put(1, Arrays.asList("test1", "test2")); Map> map2 = new HashMap>(); map2.put(1, Arrays.asList("test3", "test4")); book1.setBuckets(map1); book2.setBuckets(map2); repository.save(Arrays.asList(book1,book2)); SearchQuery searchQuery = new NativeSearchQueryBuilder() .withQuery(nestedQuery("buckets", termQuery("buckets.1", "test3"))) .build(); Page books = repository.search(searchQuery); assertThat(books.getContent().size(), is(1)); } // //todo @Ignore @Test public void shouldReturnBooksForCustomMethodsWithOrCriteria(){ Book book1 = new Book(RandomStringUtils.random(5),"test Or",System.currentTimeMillis()); Book book2 = new Book(RandomStringUtils.random(5),"test And",System.currentTimeMillis()); book1.setPrice(10L); book2.setPrice(10L); repository.save(Arrays.asList(book1, book2)); Page books = repository.findByNameOrPrice("message", 10, new PageRequest(0, 10)); assertThat(books.getContent().size(), is(2)); } @Test public void shouldGiveIterableOfBooks() { Book book1 = new Book(RandomStringUtils.random(5),"test Or",System.currentTimeMillis()); Book book2 = new Book(RandomStringUtils.random(5),"test And",System.currentTimeMillis()); book1.setPrice(10L); book2.setPrice(10L); repository.save(Arrays.asList(book1, book2)); Iterable books = repository.search(matchAllQuery()); assertThat(books, is(notNullValue())); } } ================================================ FILE: src/test/java/org/springframework/data/elasticsearch/repositories/SampleProductRepositoryTest.java ================================================ package org.springframework.data.elasticsearch.repositories; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.data.domain.PageRequest; import org.springframework.data.elasticsearch.entities.Product; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.annotation.Resource; import java.util.List; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration("classpath:/springContext-test.xml") public class SampleProductRepositoryTest { @Resource private SampleProductRepository sampleProductRepository; @Before public void emptyData(){ sampleProductRepository.deleteAll(); } @Test public void shouldReturnListOfProductsByName() { //given sampleProductRepository.index(new Product("1", "test product 1", "How great would it be if we could search for this product.", true)); sampleProductRepository .index(new Product( "2", "test Product 2", "How great would it be if we could search for this other product.", true)); //when List products = sampleProductRepository.findByName("product"); //then assertThat(products.size(), is(2)); } @Test public void shouldReturnListOfBookByNameWithPageable(){ //given sampleProductRepository.index(new Product("1", "test product 1", "How great would it be if we could search for this product.", true)); sampleProductRepository .index(new Product( "2", "test product 2", "How great would it be if we could search for this other product.", true)); //when List products = sampleProductRepository.findByName("product", new PageRequest(0,1)); //then assertThat(products.size(), is(1)); } @Test public void shouldReturnListOfProductsForGivenNameAndId(){ //given sampleProductRepository.save(new Product("1", "test product 1", "How great would it be if we could search for this product.", true)); sampleProductRepository .save(new Product( "2", "test product 2", "How great would it be if we could search for this other product.", true)); List products = sampleProductRepository.findByNameAndId("product","1"); //then assertThat(products.size(),is(1)); } } ================================================ FILE: src/test/resources/contact-test.xml ================================================ ================================================ FILE: src/test/resources/spring-context.xml ================================================ ================================================ FILE: src/test/resources/springContext-book-test.xml ================================================ ================================================ FILE: src/test/resources/springContext-test.xml ================================================