Plit00's Story

[Node.js] - Elasticsearch 페이지 출력 본문

Security/Elasticsearch

[Node.js] - Elasticsearch 페이지 출력

plit00 2023. 1. 25. 16:11

Pagination - index&tag

 

서칭을 통해 찾아본 결과 npm elasticsearch-Pagination이 있어 관련 모듈을 쓰면 된다했지만 없는걸 확인하고 

하나씩 구현함 

 

elasticsearch match_all로 검색을 한다면 10개 밖에 안보여주기 때문에 페이지네이션을 통해 출력

단, 출력하려는 index_name의 ids와 tag_index의 ids가 동일하게 매칭되어야 정상적으로 출력됨

 

client.search에서 index: ['index_name' , 'tag_index']로 검색되도 정상적으로 출력됨을 확인했지만 
원하는 바로 출력하려 했을때의 방법은 찾지 못해 하나씩 불러오는 과정으로 만듬 

 

또한, 10개밖에 안보여주는것을 size를 임의로 지정하여 전체적으로 설정할 수 있지만
원하는 데이터들이 일정 값을 넘으면 속도가 현저히 느려지기 때문에 객체변환 방식으로 페이지네이션을 구현함 

index.js

router.get('/', (req, res) =>{
	const page = parseInt(req, params.page) || 1;
    const from = (page - 1) * perPage;
    client.search({
    	index:'index_name',
		body:{
         from: from,
		 size: perPage,
         query:{
           match_all: {}
           }
         }
       }).then(indexResults => {
         const name = indexResults.hits.hits.map(hit => hit._source);
         client.search({
            index: 'tag_index',
            body: {
              from: from,
              size: perPage,
              query: {
                match_all: {}
                }
              }
          }).then(tagResults => {
          	const tag_index = tagResults.hits.hits.map(hit => hit._source);
            const total = indexResults.hits.total;
            const pages = Math.ceil(total / perPage);
            var indexData = tag_index.map(tag, i) => {
            tag.tag1 = tag_index[i].tag1;
            tag.tag2 = tag_index[i].tag2;
            tag.tag3 = tag_index[i].tag3;
            return tag;
      });
      		res.render('index', {indexData: idexData, page: page, pages: pages});
      })

 

https://www.elastic.co/guide/en/elasticsearch/reference/current/search-search.html

 

Search API | Elasticsearch Guide [8.6] | Elastic

Use with caution. Elasticsearch applies this parameter to each shard handling the request. When possible, let Elasticsearch perform early termination automatically. Avoid specifying this parameter for requests that target data streams with backing indices

www.elastic.co

원하는 레퍼런스를 통해서 임의로 query를 보낼 수 있음

Comments