# How do I get a list of search results?

**URL:** <https://discuss.elastic.co/t/how-do-i-get-a-list-of-search-results/335541>\
**Category:** Elasticsearch\
**Tags:** docker, language-clients\
**Created:** [June 8, 2023, 1:39pm UTC](https://discuss.elastic.co/t/how-do-i-get-a-list-of-search-results/335541 "2023-06-08T13:39:26Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![Nad.Chel](https://avatars.discourse-cdn.com/v4/letter/n/3be4f8/32.png) [@Nad.Chel](https://discuss.elastic.co/u/Nad.Chel)\
**Post date:** [June 8, 2023, 1:39pm UTC](https://discuss.elastic.co/t/how-do-i-get-a-list-of-search-results/335541/1 "2023-06-08T13:39:26Z")

</div>

I honestly tried to read the official tutorials. Unfortunately, I got completely bogged down: I find them hard to understand and they don't appear to give me the very specific information I need which is: how do I get a `List` of search results in Java? At this point I have these `create()` and `delete()` methods that look like this

```java
@Repository
@RequiredArgsConstructor
public class ElasticQuestionRepositoryImpl implements ElasticQuestionRepository {
    private final ElasticsearchClient client;

    @Override
    public CreateResponse create(ElasticQuestion question) {
        try {
            CreateRequest<ElasticQuestion> request = new CreateRequest.Builder<ElasticQuestion>()
                    .document(question)
                    .build();
            return client.create(request);
        } catch (IOException e) {
            throw new ElasticsearchException("Could not save an elastic entity: " + e.getMessage());
        }
    }

    @Override
    public DeleteResponse delete(ElasticQuestion question) {
        try {
            String questionId = question.getId().toString();
            DeleteRequest request = new DeleteRequest.Builder()
                    .id(questionId)
                    .build();
            return client.delete(request);
        } catch (IOException e) {
            throw new ElasticsearchException("Could not delete an elastic entity: " + e.getMessage());
        }
    }

```

Now, I somehow need to write a `getPage()` method. ChatGPT provides code that is obviosuly wrong, but I took it, altered a bit, and now I have this. It's still messy and also incomplete

```java
@Override
    public Page<QuestionResponseDto> getPage(PaginationParameters params) {
        int limit = PaginationParametersProcessor.extractMaxResults(params);
        int offset = PaginationParametersProcessor.extractFirstResultIndex(params);
        String orderByCol = PaginationParametersProcessor.extractOrderByColumn(params);
        SortOrder sortOrder = PaginationParametersProcessor.isDescending(params) ?
                SortOrder.DESC : SortOrder.ASC;
        String text = PaginationParametersProcessor.extractText(params).orElse(null); // text may be not provided

        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder()
                .from(offset)
                .size(limit)
                .sort(orderByCol, sortOrder);

        if(text != null && !text.isBlank()) {
            searchSourceBuilder.query(
                    QueryBuilders.multiMatchQuery(text, "title", "description")
            );
        }

        SearchRequest request = new SearchRequest.Builder() // StringRequest is not generic despite what the chat bot says
                .index("questions")
                .source(searchSourceBuilder) // it is an invalid argument
                .build();
    }

// here should go the ElasticQuestion → QuestionResponseDto mapping (I can write a mapper) and returning a List of all matches

```

```java
@Document(indexName = "questions")
@NoArgsConstructor
@Getter
public class ElasticQuestion implements Persistable<Long> {
    @Id
    private Long id;
    @CreatedDate
    private LocalDateTime createdDate;
    @LastModifiedDate
    private LocalDateTime modifiedDate;
    private String title;
    private String description;
    private Account owner;

    @Override
    public boolean isNew() {
        return id == null ||
                (createdDate == null && modifiedDate == null);
    }
}

```

Can you help me please? Or at least give me a reference that is comprehensive and helpful? I would be happy to receive it

---

<div class="post-metadata">

**Author:** ![dadoonet](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dadoonet/32/137187_2.png) [@dadoonet](https://discuss.elastic.co/u/dadoonet)\
**Post date:** [June 8, 2023, 1:57pm UTC](https://discuss.elastic.co/t/how-do-i-get-a-list-of-search-results/335541/2 "2023-06-08T13:57:49Z")

</div>

Would this help you to start with?

> <https://github.com/dadoonet/elasticsearch-java-client-demo/blob/main/src/test/java/fr/pilato/test/elasticsearch/hlclient/EsClientIT.java#L408-L425>

Note that this has been written by a human 😉

---

<div class="post-metadata">

**Author:** ![Nad.Chel](https://avatars.discourse-cdn.com/v4/letter/n/3be4f8/32.png) [@Nad.Chel](https://discuss.elastic.co/u/Nad.Chel)\
**Post date:** [June 8, 2023, 2:54pm UTC](https://discuss.elastic.co/t/how-do-i-get-a-list-of-search-results/335541/3 "2023-06-08T14:54:42Z")

</div>

In case it's necessary (can't edit the post any more, unfortunately)

```java
@AllArgsConstructor
@NoArgsConstructor
@Getter
@Setter
public class Page<T> {

    private List<T> dtos;
    private Long count; // btw, I need to get a count of all persisted entities too
}

```

```java
@Configuration
@EnableElasticsearchAuditing
public class ElasticConfig {
    @Bean
    public RestClient restClient() {
        return RestClient.builder(
                new HttpHost("localhost", 9200)).build();
    }

    @Bean
    public ElasticsearchTransport elasticsearchTransport() {
        return new RestClientTransport(
                restClient(), new JacksonJsonpMapper());
    }

    @Bean
    public ElasticsearchClient elasticsearchClient() {
        return new ElasticsearchClient(elasticsearchTransport());
    }
}

```

```yml
# docker_compose.yml, it's for a database too
version: '3.8'
services:
  stack_overflow_postgres:
    image: postgres:15
    container_name: stack_overflow_postgres
    restart: always
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres123
      - POSTGRES_DB=stack_overflow_postgres
    ports:
      - '5411:5432'
# the code below is generated by ChatGPT so it may be a mess too
  stack_overflow_elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:7.15.0
    container_name: stack_overflow_elasticsearch
    restart: always
    environment:
      - discovery.type=single-node
      - ELASTIC_PASSWORD=your_password
      - xpack.security.enabled=true
    ports:
      - '9200:9200'
      - '9300:9300'

  stack_overflow_app:
      build: .
      depends_on:
        - stack_overflow_postgres
        - stack_overflow_elasticsearch
      environment:
        - SPRING_DATASOURCE_URL=jdbc:postgresql://stack_overflow_postgres:5432/stack_overflow_postgres
        - SPRING_DATASOURCE_USERNAME=postgres
        - SPRING_DATASOURCE_PASSWORD=postgres123
        - SPRING_ELASTICSEARCH_REST_URIS=http://stack_overflow_elasticsearch:9200
        - SPRING_ELASTICSEARCH_REST_USERNAME=elastic
        - SPRING_ELASTICSEARCH_REST_PASSWORD=your_password
      ports:
        - '8080:8080'

```

---

<div class="post-metadata">

**Author:** ![Nad.Chel](https://avatars.discourse-cdn.com/v4/letter/n/3be4f8/32.png) [@Nad.Chel](https://discuss.elastic.co/u/Nad.Chel)\
**Post date:** [June 8, 2023, 3:19pm UTC](https://discuss.elastic.co/t/how-do-i-get-a-list-of-search-results/335541/4 "2023-06-08T15:19:20Z")

</div>

Thank you. But can you describe the steps I should take? Is my code is salvageable? For example, is the logic of first creating a `SearchSourceBuilder`, then passing it into a `SearchRequest`, then passing it into a `SearchResponse` valid? If so, how do I create the `SearchRequest` instance and, finally, retrieve a result `List` from `SearchResponse`?

---

<div class="post-metadata">

**Author:** ![dadoonet](https://sea2.discourse-cdn.com/elastic/user_avatar/discuss.elastic.co/dadoonet/32/137187_2.png) [@dadoonet](https://discuss.elastic.co/u/dadoonet)\
**Post date:** [June 8, 2023, 4:17pm UTC](https://discuss.elastic.co/t/how-do-i-get-a-list-of-search-results/335541/5 "2023-06-08T16:17:20Z")

</div>

I guess you can but I prefer to use the functional style with lambdas. 😉

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/elastic/original/3X/1/a/1ac57faf039f6b580b3f104ef42a2a89e41014de.png) [@system](https://discuss.elastic.co/u/system)\
**Post date:** [July 6, 2023, 4:17pm UTC](https://discuss.elastic.co/t/how-do-i-get-a-list-of-search-results/335541/6 "2023-07-06T16:17:25Z")

</div>

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.
