How do I get a list of search results?

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

@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

@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
@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

Would this help you to start with?

Note that this has been written by a human :wink:

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

@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
}
@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());
    }
}
# 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'

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?

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

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