본문 바로가기

반응형

전체 글

(441)
[elasticsearch] mongoDB changeStream to Elasticsearch 데이터 동기화 - sync 맞추기 mongoDB 와 Elasticsearch 데이터가 연동되어 있는 경우, 데이터 생성, 수정, 삭제가 발생할 때마다 각각의 Db를 수기로 바꿔주는 것은 매우 비효율적이다! 그래서 MongoDB의 streamchange를 사용해서 변화가 생길 때 es에도 해당 변화가 업데이트되도록 만들어 주기 ! change stream을 사용하기위해 우리는 반드시 mongoDB replica set을 사용해야 한다고 함! 그 이유는 change stream이 oplog에 의해 수행되기 때문이다. mongoDB collection에 changeStream 열기 db.collection('person').watch() 또는 Person.watch() // directly using the model Person 자체가 해당..
[Elasticsearch] synonyms 동의어 사전 추가 및 업데이트 적용하기 Elasticsearch 동의어란? 검색 엔진의 최고봉(?)인 elasticsearch에서 동의어 기능은 일상생활 검색 기능에서 필수적인 부분이다. "동의어" 라는 말 그대로 A라는 단어(검색어)를 B와 동일하게 볼 수 있도록 하는 기능이다. 지역별 단어 사용 차이라던지, 복수 단수 형 차이라던지 아니면 일반적인 동의어 영역에서 거의 비슷한 단어들이 존재하는 경우 또는 전문가와 비전문가의 언어차이 등에 동의어 기능을 사용하면 유저의 검색 경험을 훨씬 수월하게 만들 수 있습니다. examples ex1) lift => elevator ex2) houses => house ex3) tired => exausted ex4) iPod, ipod => i-Pod ex5) canine => dog elasticse..
[elasticsearch] search after란? 사용 방법 알아보기 with node.js Elasticsearch 는 한번에 최대 10,000개의 도큐먼트만 반환한다. 이 외에 size를 정해서 query를 날려 조회해올 경우에도 이전에 조회해온 것 이후부터 다시 가져올 때 필요한 기능이 search_after이다. 실습해보기 🐠 1. after_test 인덱스 생성 PUT after_test { "mappings": { "properties": { "id": { "type": "keyword" }, "place": { "type": "keyword" }, "reviews": { "type": "text" } } } } 2. 데이터 5개 입력 POST after_test/_doc { "id": 5, "place": "섬진강", "reviews": "ㄹ리뷰" } x 5 3. 일반적인 방법으로 ..
[Elasticsearch + Node.js] 좌표 거리 구하기 with script_fields arcDistance Elasticsearch db 안에 있는 데이터들의 위치와 나의 (또는 유저의) 좌표로 부터 얼마나 떨어져 있는지 거리를 나타내기 실습해보기 🐸 1. Elasticsearch distance_test 라는 index 추가 PUT distance_test { "mappings": { "properties": { "place": { "type": "text" }, "location": { "type": "geo_point" }, "reviews": { "type": "text" } } } } 2. distance_test 인덱스에 데이터 추가 POST distance_test/_doc { "place": "추어탕집", "location": [128.123123, 34.123123] } POST distanc..
[elasticsearch] dis_max란 무엇인지 알아보기, 실습하기 (bool, must와 함께 쓰기) dis_max 정확한 일치하는 문서에 더 높은 점수를 주기 위한 방법 - dis_max(DisjunctionMaxQuery에서 따온 용어) dis_max는 멀티 키워드 검색할 때, 여러 필드에서 검색 수행 시 멀티 키워드의 키워드와 동일한 키워드의 score에 더욱 높은 점수를 주는 방식이다. (하지만 반전이 있었으니...) 실습해보기 dis_max_test 라는 인덱스 생성 PUT dis_max_test { "mappings": { "properties": { "title": { "type": "text" }, "description": { "type": "text" } } } } 데이터 입력 POST dis_max_test/_doc { "title": "Autobiography of Osho", "d..
Elasticsearch geographic location query distance 거리로 가까운 곳 검색하기 1. Elasticsearch 의 GEO DATA TYPE 1) geo_point Logitude 경도, Latitude 위도를 사용하는 geo_point는 radius (반경) 내의 특정 범위 내를 검색할 수 있다. "point" 어느 지점을 딱 포인트한다 라고 이해했다 . 2) geo_shape geo_shape은 GeoJson을 사용하여 복잡한 그래프를 나타낸다. 만약 거~ 대한 박물관이 존재한다면 해당 박물관의 좌표는 한 "point"에서 끝나지않고 큰 범위를 이룰 것이다. 이 때 사용하는 것이 geo_shape 이다. 2. Elsaticsearch Geo_point search 검색 사용 방법 filter에 geo_distance를 걸어준다. filter: { geo_distance: { dis..
[mongoose] _v 필드 생성 이유 및 제거하기 갑자기 mongoDB에 새로운 db를 연결해서 데이터를 넣었는데 갑자기 처음본 _v 필드가 나왔다. 모델 스키마에 존재하지 않는데 왜지 ??? 찾다가 versionKey 값을 넣어주면 되었다. 해결 : 모델 스키마 두 번째 인자값 옵션에 versionKey: false를 작성해주기 const addressSchema: Schema = new Schema( { // 지역 region: String, // 시군구 siGunGuName: String, // 읍면동 eupMyeonDongName: String, // 연결된 주소 (pk) chainedAddress: String, }, { timestamps: { createdAt: true, updatedAt: true }, read: 'secondaryPre..
[AWS] Amazon S3 bucket 생성 방법 알아보기 (최신 업데이트) aws - Amazon s3란 ? Amazon S3 =Simple Storage Service 아마존 웹 서비스에서 제공하는 온라인 스토리지 웹 서비스 bucket, 버킷이라는 컨테이너를 생성하여 버킷에 데이터를 담아 S3에 저장한다. 덕분에 데이터를 저장하고, 보호하고, 또 언제든 어떤 디바이스로든 (클라우드 저장소너낌) 필요할 때 찾아 쓸 수 있다. Amazon S3 생성하기 1) aws 계정 로그인 계정이 없다면 이메일로 회원가입하고 진행하기! https://aws.amazon.com/ko/free 무료 클라우드 컴퓨팅 서비스 - AWS 프리 티어 Q: AWS 프리 티어란 무엇입니까? AWS 프리 티어는 고객에게 서비스별로 지정된 한도 내에서 무료로 AWS 서비스를 살펴보고 사용해 볼 수 있는 기능..
운영중인 Elasticsearch reindex alias 무중단 예제 코드 및 사용 방법 / Zero downtime reindex alias Reindex란 ? 데이터를 입력하는 것 Reindex를 하는 이유는 ? 1) index의 mapping을 수정해야 할 때 - analyzer, analyzer's definition 등을 수정 시 2) Cluster upgrade or migration - Elasticsearch version 5.x 이하일 경우 ES가 index를 읽을 수가 없어서 이런 경우에도 Reindex 진행 3) 새로운 index에 기존의 데이터를 재입력하고 싶을 때 - 하지만 Reindex라는 말 그대로 mapping 정보 등은 제외하고 only 데이터만 가져옴 Reindex 실행 전 반드시 알아야할 점은? 1) _source 가 enabled 상태인 Index만 reindex가 가능 2) mapping정보까지 카피하는 것..
[Node.js] Excel.js 사용법 총정리 / How to use Exceljs (테이블 만들기, insertRows, columns, value 등) 이번 프로젝트 중 가장 시간도 오래걸리고 어려웠던 엑셀 파일 만들어 내보내기 를 정리해서 기록으로 남기기 기존에는 xlsx를 익히고 사용했었다가 css가 유료인걸 뒤늦게 알았다.. 👼🏼 찾아보니 많은 개발자들이 이 사실에 빡치고 exceljs로 갈아타고 있다고 한다. 며칠 전 적은 xlsx 사용법 포스팅 https://blckchainetc.tistory.com/426 [Node.js] How to use xlsx with Typescript / xlsx 사용법 설치하기 Installation npm install xlsx 설치 후, 아래와 같이 두 가지의 가져오기 방법이 있다. and now you can use XLSX in 2 ways. - require ( default ) const XLSX =..
[컴퓨터 네트워크] 웹 서비스 동작 원리 / URL 뜻 / APM 동작 원리 책으로 배우는 컴퓨터 네트워크 목차 1) url 의 의미 뜻 2) 웹 서비스 동작 원리 3) APM 동작 원리 1. Url (Uniform Resource Locator ) 우리가 자주 쓰는 url 주소는 아래의 구성으로 이루어져있다. 호스트는 우리가 알기 쉽게 만든 "이름"이라고 생각하면 되고 사실상 ip 주소를 말한다. 호스트: ip 를 저장하는 DNS 서비스로 해당 호스트명으로 ip를 찾아 사용한다. https://www.naver.com/shopping/payment [https] :// [www.naver.com] / [shopping/payment] [프로토콜] : // [host호스트] / [path 내부경로] 2. 웹 서비스 동작 원리 1. 사용자가 웹 브라우저에 url 주소 입력 2. c..
[JavaScript] reduce 개념 사용법 알아보기 Reduce : reduce() 매서드는 배열의 각 요소에 대해 주어진 함수를 실행, 하나의 결과값을 반환한다. 반환값은 number, object, array 등이 있다. * reduce는 배열에 적용되는 함수이다. Reduce의 인자값 1. 누산기 (acc) 2. 현재값 (cur) 3. 현재 인덱스 (idx) 4. 원본 배열 (src) reduce의 첫 번째 인자값이 reduce의 특징을 잘 말해준다. acc 누산기 = 최종 집합 결과물이라고 생각하면 쉽다, 내가 설정한 함수가 적용된 값이 acc 인자값으로 할당되고 각 ele요소 반복하면서 acc의 값도 계속해서 바뀌게 된다. 처음 개념을 읽었을 때 바로 이해하기 어려웠는데, 아래 예시처럼 console.log를 찍어 어떻게 돌아가는지 눈으로 확인하..
map vs reduce 개념 차이 성능 속도 비교 Map & Reduce map 과 reduce 모두 항상 array에 사용한다. ex. [1,2,3,4].map(() => {}) [{a:1}, {b:2}, {c:3}].reduce(() => {}) Map map은 항상 기존의 array가 가진 동일한 수의 elements를 담은 array를 반환한다. 만약 기존 array 의 elements가 5개라면 반환되는 array의 elements도 5개이다. array의 각각의 개별 element에 변화를 주고 싶을 때 map을 사용한다. example) const array = [1,2,3,4]; const mapArray = array.map((ele) => { return Math.pow(ele, 2); }); console.log(mapArray);)..
Excel how to custom Number format 숫자 서식 사용자 지정 커스텀하기 / -0 을 0으로 바꾸기 음수 node.js + typescript + exceljs 로 엑셀 파일 생성을 하던 중, db에서 받은 데이터는 1000, 0, -500 이렇게 실수인 경우 모두 - 를 붙여서 출력해야 했다. numFmt : '#,##0' 은 123,400 이렇게 나오고 numFmt : '-#,##0' 은 -123,500 이렇게 나온다. 그래서 처음에는 '-#,##0'으로 사용했다. 그런데 내가 받은 데이터가 1000, 0, -500 이라면 '-#,##0'이 적용되어 나오는 형식이 아래 박스의 결과였다. The data I got from db was [100, 0, -500] and I had to show them in Excel file as negative. so first I tried exceljs numFmt..
[Exceljs] worksheet.columns location 엑셀 컬럼 위치 지정하기 node.js + typescript + exceljs 로 엑셀 파일 생성 및 내보내기를 진행하다가 Exceljs의 addTable 로 테이블을 작성했었다. 이후에 코드리뷰를 받고 table 생성을 아예 하지않고 아예 columns 추가 및 데이터를 InsertRows로 생성하도록 변경했다. 여기서 내가 어려움이 있었던 부분은 I decided to use "worksheet.columns" + "insertRows" instead of using "addTable" function because the data I got from db is an array of objects and I had to refine the data for the rows of table again. but I can jus..
[mongoDB/mongoose] Schema hasn't been registered for model / Populate Schema hasn't been registered for model error cases below schema const userSchema = new Schema( { name: String, friends: [{ type: Schema.Types.ObjectId, ref: 'friends' }], }, { timestamps: false, read: 'secondaryPreferred', versionKey: false, }, ); 스키마 User에 friends라는 다른 모델을 Ref 해놓고 mongoose Populate를 하다가 나온 에러! Wrong usage const getFriends = async (userIdx, projection) => { return UserModel.fi..
Typescript Error: Property 'user' does not exist on type 'Request' Typescript import { Request, Response } from 'express'; const exec = async (req: Request, res: Response, next: Function): Promise => { const { idx } = req.user; const { restaurantIdx } = req.params; . . . }; export default { exec }; 빨간 줄이 간 .user You can see the res line above, the error is : Error : TS2339: Property 'user' does not exist on type 'Request >'. 기본적으로 express에서 가져온 Request에는 user라는..
[No overload matches this call] is not assignable to type 'RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>> [No overload matches this call] ~ is not assignable to type 'RequestHandler TS2769: No overload matches this call. The last overload gave the following error. Argument of type '(req: Request, res: Response, next: NextFunction) => any' is not assignable to parameter of type 'RequestHandlerParams'. Type '(req: Request, res: Response, next: NextFunction) => any' is not assignable to type 'RequestHa..
[node.js] setHeader content-disposition 파일명 한글 깨짐 / TypeError - Invalid character in header content ["Content-Disposition"] node.js에서 엑셀 파일 생성 및 내보내기 (다운로드) 를 진행할 때 파일명에 한글이 들어가면 아래와 같은 에러가 나온다. res.setHeader( 'Content-Disposition', `attachment; filename=파일명예시.xlsx`, ); TypeError - Invalid character in header content ["Content-Disposition"] 해결법 1. 먼저 한글 String에 인코딩을 해주고 2. filename 바로 뒤에 [ *utf-8'' ] 를 적는다. res.setHeader( 'Content-Disposition', `attachment; filename*utf-8''=encodeURI('파일명예시').xlsx`, ); 그럼 엑셀 파일명이 내가 ..
[Joi] 특정 필드 날짜보다 특정일을 초과하면 안되도록 설정하기 아래와 같이 startDate와 finishDate가 있다. 여기서 startDate와 finishDate가 최대 90일까지 가능하도록 (91일 부터는 설정이 되지 않도록) 만들기 There are startDate, finishDate in the following box. I'd like to make the the max days between them 90 days. const validationSettings = { startDate: Joi.date() .required() .format('YYYY-MM-DD') .max(Joi.ref('finishDate')) .label('시작 날짜'), finishDate: Joi.date() .required() .format('YYYY-MM-DD') ..
[Postman] 엑셀 파일 다운로드 API 요청 보내기 / 포스트맨 / how to send Download API node.js 로 엑셀파일 생성 및 다운로드 코드를 작성했는데 postman API "SEND"를 누르면 계속 깨진 글자들이 나왔다. 다운로드 API 경우 postman 사용법을 찾아보니 I was trying to create and export .xlsx file with Node.js but whenever press "Send" in postman to check my API, it gave me broken result like below. 아래 사진처럼 "send" 오른쪽 화살표 표시를 누르면 "Send and Download"가 있다. 이걸 눌러주면 파일 다운로드를 어디에 할지 팝업이 뜨고 잘 다운된다. You can press the little arrow just next to the "..
Node.js excel file download 엑셀 다운로드 사용법 예제 Node.js Typescript Exceljs 로 엑셀파일 다운로드되도록 만들기 How to download exce(.xlsx) file in Node.js with TypeScript const exec = async (res) => { workbook 및 worksheet 생성 res.setHeader( 'Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', ); res.setHeader( 'Content-Disposition', `attachment; filename=${fileName}.xlsx`, ); await workbook.xlsx.write(res); }; export default { e..
[Node.js] How to use xlsx with Typescript / xlsx 사용법 xlsx 를 사용하기 전 엑셀에 CSS 등 꾸미는 것 (배경 색, 정렬 등등) 이 필수라면 xlsx보다 excel.js 를 권합니다! (xslx 실컷 사용하다가 css 가 유료인걸 뒤늦게 알고 Exceljs로 옮김) 👇👇👇 https://blckchainetc.tistory.com/entry/Nodejs-Exceljs-%EC%82%AC%EC%9A%A9%EB%B2%95-%EC%B4%9D%EC%A0%95%EB%A6%AC-How-to-use-Exceljs-%ED%85%8C%EC%9D%B4%EB%B8%94-%EB%A7%8C%EB%93%A4%EA%B8%B0-insertRows-columns-value-%EB%93%B1 [Node.js] Excel.js 사용법 총정리 / How to use Exceljs (테이블 ..
[Javascript] 날짜 더하고 빼기 / How to set or add months, days, hours to Date / moment 라이브러리 1. new Date() function const today = new Date(); console.log(today); const ACertainDay = new Date('2020-01-01'); console.log('a certain day =', ACertainDay); const ACertainDay2 = new Date(2022, 1, 1,); console.log(ACertainDay2) console.log result new Date()은 () 안이 비어있으면 디폴트로 "현재"를 반환하고, 'YYYY-MM-DD' string형태로 값을 넣을 수 있다. 값을 넣는 형태는 (2020,1,1) 이렇게도 가능하다. It returns date, default is 'now' (when the..
[JavaScript] Convert a Unix timestamp to time / 유닉스 시간으로 변환하기 유닉스 시간 -----> 날짜로 변환하기 : How to convert a Unix timestamp to time const unix_timestamp = 1582416000; const date = new Date(unix_timestamp * 1000); console.log('date=', date); 날짜 ------> 유닉스 시간으로 변환하기 : How to convert time to a Unix timestamp const time = new Date('2022-06-24'); const unixTime = time.getTime(); console.log('unixTime=', unixTime)
[Joi] callStack: Error: item added into group finishDate created a dependencies error\n Joi 를 사용하다가 나온 에러 Joi callStack: Error: item added into group finishDate created a dependencies error\n My code : const validationSettings = { index: Joi.number().integer().required().label('index'), startDate: Joi.date() .format('YYYY-MM-DD') .min( Joi.ref('finishDate', { adjust: finishDate => new Date(finishDate.setDate(finishDate.getDate() - 89)), }), ) .label('startDate'), finishDate: Joi.da..
[Elasticsearch] curl create index, delete index 인덱스 생성 삭제 curl index create / 인덱스 생성 & curl index delete / 인덱스 삭제 + Elasticsearch AWS APIKEY 로 요청 보내기 CREATE Index 생성 요청 / to create an index curl -XPUT "{host}:{port}/{index}" API KEY 필요한 경우 / with an API KEY curl -H "Authorization:ApiKey [your API KEY]" -XPUT "{host}:{port}/{index}" DELETE Index 삭제 요청 / to delete an index curl -XDELETE "{host}:{port}/{index}" API KEY 필요한 경우 / with an API KEY curl -H "Au..
[Javascript/Typescript] Promise returned from forEach argument is ignored 객체 모음의 배열에서 [{}, {}, ...] forEach를 사용하면서 안에 await 를 사용했더니 When I used async/await in forEach, the Error below occurred. [ERROR]: Promise returned from forEach argument is ignored 위 에러가 나왔다. forEach 는 synchronous function을 예상하는데, async function은 프로미스를 반환하고, caller는 반환받은 프로미스 값으로 무언가를 해야할 책임(?)이 있다. 그런데 forEach는 반환값으로 무언가를 하는 적합하지 않아서 (그냥 반환값없이 각각의 ele 요소를 call할 뿐) 그냥 이것을 무시한다. forEach 대신 for문 또는 ..

반응형