Search in sources :

Example 1 with SearchDocument

use of org.springframework.data.elasticsearch.core.document.SearchDocument in project spring-data-elasticsearch by spring-projects.

the class DocumentAdaptersUnitTests method searchResponseShouldReturnContainsKey.

// DATAES-628
@Test
public void searchResponseShouldReturnContainsKey() {
    Map<String, DocumentField> fields = new LinkedHashMap<>();
    fields.put("string", new DocumentField("string", Collections.singletonList("value")));
    fields.put("bool", new DocumentField("bool", Arrays.asList(true, true, false)));
    SearchHit searchHit = new SearchHit(123, "my-id", new Text("type"), fields, null);
    SearchDocument document = DocumentAdapters.from(searchHit);
    assertThat(document.containsKey("string")).isTrue();
    assertThat(document.containsKey("not-set")).isFalse();
}
Also used : DocumentField(org.elasticsearch.common.document.DocumentField) SearchHit(org.elasticsearch.search.SearchHit) Text(org.elasticsearch.common.text.Text) LinkedHashMap(java.util.LinkedHashMap) SearchDocument(org.springframework.data.elasticsearch.core.document.SearchDocument) Test(org.junit.jupiter.api.Test)

Example 2 with SearchDocument

use of org.springframework.data.elasticsearch.core.document.SearchDocument in project spring-data-elasticsearch by spring-projects.

the class DocumentAdaptersUnitTests method shouldAdaptReturnedMatchedQueries.

// DATAES-979
@Test
@DisplayName("should adapt returned matched queries")
void shouldAdaptReturnedMatchedQueries() {
    SearchHit searchHit = new SearchHit(42);
    searchHit.matchedQueries(new String[] { "query1", "query2" });
    SearchDocument searchDocument = DocumentAdapters.from(searchHit);
    List<String> matchedQueries = searchDocument.getMatchedQueries();
    assertThat(matchedQueries).isNotNull();
    assertThat(matchedQueries).hasSize(2);
    assertThat(matchedQueries).isEqualTo(Arrays.asList("query1", "query2"));
}
Also used : SearchHit(org.elasticsearch.search.SearchHit) SearchDocument(org.springframework.data.elasticsearch.core.document.SearchDocument) Test(org.junit.jupiter.api.Test) DisplayName(org.junit.jupiter.api.DisplayName)

Example 3 with SearchDocument

use of org.springframework.data.elasticsearch.core.document.SearchDocument in project spring-data-elasticsearch by spring-projects.

the class DocumentAdaptersUnitTests method shouldAdaptSearchResponseSource.

// DATAES-628, DATAES-848
@Test
public void shouldAdaptSearchResponseSource() {
    BytesArray source = new BytesArray("{\"field\":\"value\"}");
    SearchShardTarget shard = new SearchShardTarget("node", new ShardId("index", "uuid", 42), null);
    SearchHit searchHit = new SearchHit(123, "my-id", new Text("type"), null, null);
    searchHit.shard(shard);
    searchHit.sourceRef(source).score(42);
    searchHit.version(22);
    searchHit.setSeqNo(1);
    searchHit.setPrimaryTerm(2);
    SearchDocument document = DocumentAdapters.from(searchHit);
    assertThat(document.getIndex()).isEqualTo("index");
    assertThat(document.hasId()).isTrue();
    assertThat(document.getId()).isEqualTo("my-id");
    assertThat(document.hasVersion()).isTrue();
    assertThat(document.getVersion()).isEqualTo(22);
    assertThat(document.getScore()).isBetween(42f, 42f);
    assertThat(document.get("field")).isEqualTo("value");
    assertThat(document.hasSeqNo()).isTrue();
    assertThat(document.getSeqNo()).isEqualTo(1);
    assertThat(document.hasPrimaryTerm()).isTrue();
    assertThat(document.getPrimaryTerm()).isEqualTo(2);
}
Also used : ShardId(org.elasticsearch.index.shard.ShardId) BytesArray(org.elasticsearch.common.bytes.BytesArray) SearchHit(org.elasticsearch.search.SearchHit) SearchShardTarget(org.elasticsearch.search.SearchShardTarget) Text(org.elasticsearch.common.text.Text) SearchDocument(org.springframework.data.elasticsearch.core.document.SearchDocument) Test(org.junit.jupiter.api.Test)

Example 4 with SearchDocument

use of org.springframework.data.elasticsearch.core.document.SearchDocument in project spring-data-elasticsearch by spring-projects.

the class ReactiveElasticsearchTemplate method doFindForResponse.

private <T> Mono<SearchDocumentResponse> doFindForResponse(Query query, Class<?> clazz, IndexCoordinates index) {
    return Mono.defer(() -> {
        SearchRequest request = requestFactory.searchRequest(query, clazz, index);
        request = prepareSearchRequest(request, false);
        SearchDocumentCallback<?> documentCallback = new ReadSearchDocumentCallback<>(clazz, index);
        // noinspection unchecked
        SearchDocumentResponse.EntityCreator<T> entityCreator = searchDocument -> ((Mono<T>) documentCallback.toEntity(searchDocument)).toFuture();
        return doFindForResponse(request, entityCreator);
    });
}
Also used : DefaultReactiveClusterOperations(org.springframework.data.elasticsearch.core.cluster.DefaultReactiveClusterOperations) QueryBuilders(org.elasticsearch.index.query.QueryBuilders) ElasticsearchPersistentEntity(org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentEntity) PersistentPropertyAccessor(org.springframework.data.mapping.PersistentPropertyAccessor) BulkFailureException(org.springframework.data.elasticsearch.BulkFailureException) DeleteRequest(org.elasticsearch.action.delete.DeleteRequest) IndexRequest(org.elasticsearch.action.index.IndexRequest) ReindexRequest(org.springframework.data.elasticsearch.core.reindex.ReindexRequest) VersionInfo(org.springframework.data.elasticsearch.support.VersionInfo) MappingElasticsearchConverter(org.springframework.data.elasticsearch.core.convert.MappingElasticsearchConverter) Map(java.util.Map) RoutingResolver(org.springframework.data.elasticsearch.core.routing.RoutingResolver) IndicesOptions(org.elasticsearch.action.support.IndicesOptions) DeleteByQueryRequest(org.elasticsearch.index.reindex.DeleteByQueryRequest) ElasticsearchPersistentProperty(org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty) GetRequest(org.elasticsearch.action.get.GetRequest) ReactiveEntityCallbacks(org.springframework.data.mapping.callback.ReactiveEntityCallbacks) IndexCoordinates(org.springframework.data.elasticsearch.core.mapping.IndexCoordinates) UpdateQuery(org.springframework.data.elasticsearch.core.query.UpdateQuery) BulkItemResponse(org.elasticsearch.action.bulk.BulkItemResponse) ReactiveClusterOperations(org.springframework.data.elasticsearch.core.cluster.ReactiveClusterOperations) Collection(java.util.Collection) BulkResponse(org.elasticsearch.action.bulk.BulkResponse) IndexQuery(org.springframework.data.elasticsearch.core.query.IndexQuery) Collectors(java.util.stream.Collectors) List(java.util.List) Version(org.elasticsearch.Version) NonNull(org.springframework.lang.NonNull) LogFactory(org.apache.commons.logging.LogFactory) SearchDocument(org.springframework.data.elasticsearch.core.document.SearchDocument) ApplicationContextAware(org.springframework.context.ApplicationContextAware) Document(org.springframework.data.elasticsearch.core.document.Document) ReactiveBeforeConvertCallback(org.springframework.data.elasticsearch.core.event.ReactiveBeforeConvertCallback) ReactiveAfterSaveCallback(org.springframework.data.elasticsearch.core.event.ReactiveAfterSaveCallback) SeqNoPrimaryTerm(org.springframework.data.elasticsearch.core.query.SeqNoPrimaryTerm) Suggest(org.springframework.data.elasticsearch.core.suggest.response.Suggest) GetResult(org.elasticsearch.index.get.GetResult) Tuple2(reactor.util.function.Tuple2) MultiGetRequest(org.elasticsearch.action.get.MultiGetRequest) HashMap(java.util.HashMap) Query(org.springframework.data.elasticsearch.core.query.Query) SearchRequest(org.elasticsearch.action.search.SearchRequest) BulkOptions(org.springframework.data.elasticsearch.core.query.BulkOptions) EntityReader(org.springframework.data.convert.EntityReader) SearchDocumentResponse(org.springframework.data.elasticsearch.core.document.SearchDocumentResponse) WriteRequest(org.elasticsearch.action.support.WriteRequest) DocumentAdapters(org.springframework.data.elasticsearch.core.document.DocumentAdapters) ByQueryResponse(org.springframework.data.elasticsearch.core.query.ByQueryResponse) ElasticsearchConverter(org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter) ReactiveAfterLoadCallback(org.springframework.data.elasticsearch.core.event.ReactiveAfterLoadCallback) IndexResponse(org.elasticsearch.action.index.IndexResponse) Nullable(org.springframework.lang.Nullable) UpdateResponse(org.springframework.data.elasticsearch.core.query.UpdateResponse) UpdateByQueryRequest(org.elasticsearch.index.reindex.UpdateByQueryRequest) BulkByScrollResponse(org.elasticsearch.index.reindex.BulkByScrollResponse) Publisher(org.reactivestreams.Publisher) Mono(reactor.core.publisher.Mono) UpdateRequest(org.elasticsearch.action.update.UpdateRequest) BeansException(org.springframework.beans.BeansException) SimpleElasticsearchMappingContext(org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext) ReactiveElasticsearchClient(org.springframework.data.elasticsearch.client.reactive.ReactiveElasticsearchClient) DocWriteResponse(org.elasticsearch.action.DocWriteResponse) ApplicationContext(org.springframework.context.ApplicationContext) SuggestBuilder(org.elasticsearch.search.suggest.SuggestBuilder) Flux(reactor.core.publisher.Flux) HttpStatus(org.springframework.http.HttpStatus) AdaptibleEntity(org.springframework.data.elasticsearch.core.EntityOperations.AdaptibleEntity) ReactiveAfterConvertCallback(org.springframework.data.elasticsearch.core.event.ReactiveAfterConvertCallback) NoSuchIndexException(org.springframework.data.elasticsearch.NoSuchIndexException) DefaultRoutingResolver(org.springframework.data.elasticsearch.core.routing.DefaultRoutingResolver) Log(org.apache.commons.logging.Log) NativeSearchQueryBuilder(org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder) BulkRequest(org.elasticsearch.action.bulk.BulkRequest) ReindexResponse(org.springframework.data.elasticsearch.core.reindex.ReindexResponse) UncategorizedElasticsearchException(org.springframework.data.elasticsearch.UncategorizedElasticsearchException) Assert(org.springframework.util.Assert) SearchRequest(org.elasticsearch.action.search.SearchRequest) Mono(reactor.core.publisher.Mono) SearchDocumentResponse(org.springframework.data.elasticsearch.core.document.SearchDocumentResponse)

Example 5 with SearchDocument

use of org.springframework.data.elasticsearch.core.document.SearchDocument in project spring-data-elasticsearch by spring-projects.

the class SearchHitMapping method mapInnerDocuments.

/**
 * try to convert the SearchDocument instances to instances of the inner property class.
 *
 * @param searchHits {@link SearchHits} containing {@link Document} instances
 * @param type the class of the containing class
 * @return a new {@link SearchHits} instance containing the mapped objects or the original inout if any error occurs
 */
private SearchHits<?> mapInnerDocuments(SearchHits<SearchDocument> searchHits, Class<T> type) {
    if (searchHits.isEmpty()) {
        return searchHits;
    }
    try {
        NestedMetaData nestedMetaData = searchHits.getSearchHit(0).getContent().getNestedMetaData();
        ElasticsearchPersistentEntityWithNestedMetaData persistentEntityWithNestedMetaData = getPersistentEntity(mappingContext.getPersistentEntity(type), nestedMetaData);
        if (persistentEntityWithNestedMetaData.entity != null) {
            List<SearchHit<Object>> convertedSearchHits = new ArrayList<>();
            Class<?> targetType = persistentEntityWithNestedMetaData.entity.getType();
            // convert the list of SearchHit<SearchDocument> to list of SearchHit<Object>
            searchHits.getSearchHits().forEach(searchHit -> {
                SearchDocument searchDocument = searchHit.getContent();
                Object targetObject = converter.read(targetType, searchDocument);
                convertedSearchHits.add(new // 
                SearchHit<Object>(// 
                searchDocument.getIndex(), // 
                searchDocument.getId(), // 
                searchDocument.getRouting(), // 
                searchDocument.getScore(), // 
                searchDocument.getSortValues(), // 
                searchDocument.getHighlightFields(), // 
                searchHit.getInnerHits(), // 
                persistentEntityWithNestedMetaData.nestedMetaData, // 
                searchHit.getExplanation(), // 
                searchHit.getMatchedQueries(), targetObject));
            });
            String scrollId = null;
            if (searchHits instanceof SearchHitsImpl) {
                scrollId = ((SearchHitsImpl<?>) searchHits).getScrollId();
            }
            return new // 
            SearchHitsImpl<>(// 
            searchHits.getTotalHits(), // 
            searchHits.getTotalHitsRelation(), // 
            searchHits.getMaxScore(), // 
            scrollId, // 
            convertedSearchHits, // 
            searchHits.getAggregations(), searchHits.getSuggest());
        }
    } catch (Exception e) {
        throw new UncategorizedElasticsearchException("Unable to convert inner hits.", e);
    }
    return searchHits;
}
Also used : NestedMetaData(org.springframework.data.elasticsearch.core.document.NestedMetaData) ArrayList(java.util.ArrayList) UncategorizedElasticsearchException(org.springframework.data.elasticsearch.UncategorizedElasticsearchException) UncategorizedElasticsearchException(org.springframework.data.elasticsearch.UncategorizedElasticsearchException) SearchDocument(org.springframework.data.elasticsearch.core.document.SearchDocument)

Aggregations

SearchDocument (org.springframework.data.elasticsearch.core.document.SearchDocument)11 SearchHit (org.elasticsearch.search.SearchHit)7 Test (org.junit.jupiter.api.Test)7 Text (org.elasticsearch.common.text.Text)5 LinkedHashMap (java.util.LinkedHashMap)4 DocumentField (org.elasticsearch.common.document.DocumentField)4 ArrayList (java.util.ArrayList)2 Map (java.util.Map)2 ShardId (org.elasticsearch.index.shard.ShardId)2 SearchShardTarget (org.elasticsearch.search.SearchShardTarget)2 DisplayName (org.junit.jupiter.api.DisplayName)2 UncategorizedElasticsearchException (org.springframework.data.elasticsearch.UncategorizedElasticsearchException)2 Collection (java.util.Collection)1 HashMap (java.util.HashMap)1 List (java.util.List)1 Collectors (java.util.stream.Collectors)1 Log (org.apache.commons.logging.Log)1 LogFactory (org.apache.commons.logging.LogFactory)1 Version (org.elasticsearch.Version)1 DocWriteResponse (org.elasticsearch.action.DocWriteResponse)1