Búsqueda de sitios web

javascript - ¿Cómo usar el mapeo de TypeScript para la respuesta de ElasticSearch?


¿Cómo configuro la interfaz Post SearchResult al valor de retorno de la búsqueda?

No puedo configurar la interfaz para obtener los resultados de retorno. Puedes revisar el código a continuación.

dependencias :

   "@nestjs/elasticsearch": "^8.1.0",
   "@elastic/elasticsearch": "^8.2.1",
   "@types/elasticsearch": "^5.0.40",

interfaz Publicación :

export interface PostSearchResultInterface {
    hits: {
        total: {
            value: number;
        };
        hits: Array<{
            total: {
                value: number;
            }
            _source: PostSearchBodyInterface;
        }>;
    };
}

código :

     const  search  = await this.elasticsearchService.search<PostSearchBodyInterface>({
                index: this.index,
                from: offset,
                size: limit,
                body: {
                    query: {
                        bool: {
                            should: {
                                multi_match: {
                                    query: text,
                                    fields: ['title', 'story', 'other_titles']
                                }
                            },
                            filter: {
                                range: {
                                    id: {
                                        gte: startId
                                    }
                                }
                            }
                        },
                    },
                    sort: {
                        id: {
                            order: 'asc'
                        }
                    }
                }
            }) ;


             // error here 
            let count = search.hits.total.value
           
            const hits = search.hits.hits;
            const results = hits.map((item) => item._source);
            return {
                count : startId ? separateCount : count,
                results
            }

error TS2339: La propiedad 'value' no existe en el tipo 'number | SearchTotalHits'. La propiedad 'value' no existe en el tipo 'number'.

ERROR: let count = search.hits.total.value

Respuesta #1

Suponiendo que las dependencias son (como se plantea en la pregunta) :

"@nestjs/elasticsearch": "^8.1.0",
"@elastic/elasticsearch": "^8.2.1",
"@types/elasticsearch": "^5.0.40",

Primero, crea un tipo dedicado para el documento indexado, por ejemplo :

export type Document = { 
  title: string, 
  tags: string[]
};

Luego, simplemente busque documentos :

const a = await this.elastic.search<Document>({ //...request... });

const total = a.hits.total;
const documents = a.hits.hits.map(document => {
  // query metadata fields returned by elastic
  document._id;

  // get fields for <Document> type
  document._source.title...
  document._source.tags...
})

Artículos relacionados