override def query()

in backend/app/services/index/ElasticsearchResources.scala [378:428]


  override def query(parameters: SearchParameters, context: SearchContext): Attempt[SearchResults] = {
    val topLevelSearchQuery = buildQueryStringQuery(parameters.q)

    val req =
      search(indexName)
        .query(
          must(should(
            topLevelSearchQuery,
            buildMetadataQuery(parameters)
          )).filter(SearchContext.buildFilters(parameters, context))
        )
        .fetchContext(FetchSourceContext(fetchSource = true, excludes = Set(IndexFields.text, s"${IndexFields.ocr}.*")))
        .from(parameters.from)
        .size(parameters.size)
        .highlighting(HighlightFields.searchHighlights(topLevelSearchQuery))
        .aggs(
          termsAgg(IndexAggNames.collection, IndexFields.collectionRaw),
          termsAgg(IndexAggNames.ingestion, IndexFields.ingestionRaw),
          dateHistogramAgg(IndexAggNames.createdAt, IndexFields.createdAt).calendarInterval(DateHistogramInterval.Month),
          termsAgg(IndexAggNames.mimeTypes, "metadata." + IndexFields.metadata.mimeTypesRaw).size(MimeDetails.displayMap.size * 2),
          termsAgg(IndexAggNames.flags, IndexFields.flagsRaw).size(Flags.all.size),
          nestedAggregation(IndexAggNames.workspace, IndexFields.workspacesField).subaggs(
            termsAgg(IndexAggNames.workspace, s"${IndexFields.workspacesField}.${IndexFields.workspaces.workspaceId}")
          )
        )

    execute {
      parameters.sortBy match {
        case Relevance => req
        case SizeAsc => req.sortBy(fieldSort(IndexFields.metadataField + "." + IndexFields.metadata.fileSize).asc())
        case SizeDesc => req.sortBy(fieldSort(IndexFields.metadataField + "." + IndexFields.metadata.fileSize).desc())
        case CreatedAtAsc => req.sortBy(fieldSort(IndexFields.createdAt).asc())
        case CreatedAtDesc => req.sortBy(fieldSort(IndexFields.createdAt).desc())
      }
    }.map { resp =>
      val hits = resp.totalHits
      val took = resp.took
      val results = resp.to[SearchResult].toList

      SearchResults(hits, took, parameters.page, parameters.pageSize, results,
        Set(
          Aggregations.collections(resp),
          Aggregations.months(resp),
          Aggregations.mimeTypes(resp)
          // Disabled as sometimes the counts showed more results than the hits you got back once you ticked the filter
          // TODO MRB: re-enable once we determine why we sometimes have duplicate entries in the `workspace` field
          //Aggregations.workspaces(resp)
        )
      )
    }
  }