MYSQL ElasticSearch

BodeulMaNN·2023년 4월 5일
0

p80
REST API:POST,GET, DELETE

POST:추가할때
GET:조회할때
PUT: 수정할때
DELETE: 삭제할때

P82
get_cat/indices

p88
MySQL ElasticSearch
관계형DB(SQL) NoSQL
테이블(표) 인덱스
레코드(행) 도큐먼트
컬럼(열) 필드
스키마 매핑

p89
CRUD동작:
Create(저장), Read(조회), Update(수정), Delete(삭제)
MySQL
insert, select update, delete

p90
put index1(index 생성)
get index1(index 조회)
delete index1(index 삭제)

p91
put index2/_doc/1
{
"name":"mike",
"age":25,
"gender":"M"
}

get index2

get index2/_doc/1

p92
put index2/_doc/2
{
"name":"mike",
"country":"france"
}

put index2/_doc/2

put index2/_doc/3
{
"name":"mike",
"age":"25",
"country":"france"
}

"25" -> 25 자동형변환

p93
index2/_search :컨텐츠 확인

p94
사실 도큐먼트 업데이트를 위한 특별한 API가 있는것은 아님
=>업데이트 사용을 꺼린다.(업데이트가 힘들고 Doc 통째로 새로 덮어씀)

post index2/_update/1
{
"doc":{"name":"lee"}
}

p95
delete index2/_doc/2

p96-97 bulk
p97_4줄: json(x), ndjson(o)

p99 매핑

elasticsearch(elastic 회사 제작 검색 엔진, 오픈소스 루씬을 가져다 패키징)

json->루씬

a. 다이나믹 매핑(자동)
b. 명시적 매핑(int16)

p100
다이나믹 매핑방법
원본 데이터타잎 -> 다이나믹 매핑
null 필드추가x
boolean(T/F) boolean
float float
integer long
object(딕셔너리) object(딕셔너리)
string string(date, text/keyword)

매핑 상태를 확인
get index2/_mapping

p101
명시적 매핑
put index3
{
"mappings":
{
"properties":
{
"age":{"type":"short"},
"name":{"type":"text"},
"gender":{"type":"keyword"}
}
}
}
결과:
{
"acknowledged" : true,
"shards_acknowledged" : true,
"index" : "index3"
}
get index3/_mapping
결과:
{
"index3" : {
"mappings" : {
"properties" : {
"age" : {
"type" : "short"
},
"gender" : {
"type" : "keyword"
},
"name" : {
"type" : "text"
}
}
}
}
}

get index3/_mapping

p102 _-6줄
명시적 매핑이 되면, 새로운 필드("country")추가 가능
기존 정의는 바꿀 수 없다.

p103
데이터 타입
텍스트 text :전문검색 :텍스트 분석기 "축구의 역사"=>"축구", "의", "역사"(토큰)=>"축구", "역사"(용어)
P122~123 분석기(장문의 글)->(토크나이저)->(토큰필터)
tf-idf :머신러닝책(p564) vs 엘라스틱책(p146,147)
P125 그림 3.32
I love Cute Dog.(문서 1)
the 10 most loving dog breeds.(문서2)

 분석기(문서 1, 문서2): 역인덱싱

용어	문서번호
10	2
beeds	2
cute	1
dog	1, 2
i	1
love	1, 2
most	2

P104 we offer solusions for ~
["we", "offer", "solutions", ...]
MySQL: %solutions%

 keyword	:정렬, 집계 ["축구의 역사", "축구의 실무"]

정수 byte :8비트(-2^7~2^7-1)(0을 포함해서 카운트)
short :16비트
integer :32비트
long :62비트
실수 float :32비트
double :64비트
half_float :16비트
scaled_float :float 데이트에 특정 값을 곱해서 정수형으로 바꾼 데이터

0.1 10 1
0.2
10 2
0.4 *10 4

ipv4:32 비트주소체계 xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx 192.168.0.1 (40억개 정도)
ipv6:128 비트주소체계 192.168.0.1 192.168.0.1 192.168.0.1 192.168.0.1

p105 명시적 매핑
put text_index
{
"mappings":
{
"properties":
{
"contents":{"type":"text"}
}
}
}

p106
put text_index/_doc/1
{
"contents":"beautiful day"
}

p107 키워드 타입
beautiful, day
[beautiful day, bad day, soso day]

put keyword_index
{
"mappings":{
"properties":{
"contents":{"type"
:"keyword"}
}
}
}

p108
get keyword_index/_search
{
"query":{
"match": {
"contents": "beautiful day"
}
}
}

p109

p110
put multifield_index/_doc/1
{
"message":"1 document",
"contents":"beautiful day"
}
put multifield_index/_doc/2
{
"message":"2 document",
"contents":"beautiful day"
}
put multifield_index/_doc/3
{
"message":"3 document",
"contents":"wonderful day"
}

get multifield_index/_search
{
"query":{
"match":{
"contents":"day"
}
}
}

p111
"size":0 = 집계결과만 보여준다.
get multifield_index/_search
{
"size":0,
"aggs":{
"contents":{
"terms":{
"field":"contents.keyword"
}
}
}
}

p112인덱스 템플릿
testindex1, test_index2, test_index3 (Ex, test학급1, test학급2, ...): 설정이 동일한 인덱스들
p113템플릿 생성
PUT _index_template/test_template
{
"index_patterns":["test
*"],
"priority" : 1,
"template":{
"settings":{
"number_of_shards":3,
"number_of_replicas":1
},
"mappings":{
"properties":{
"name":{"type":"text"},
"age":{"type":"short"},
"gender":{"type":"keyword"}
}
}
}
}

put test_index1/_doc/1
{
"name":"kim",
"age":10,
"gender":"male"
}
get test_index1
p115템플릿 적용

put train_index1/_doc/1
{
"name":"kim",
"age":10,
"gender":"male"
}

get trian_index1

결과:
{
"trian_index1" : {
"aliases" : { },
"mappings" : {
"properties" : {
"age" : {
"type" : "long"
},
"gender" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
},
"name" : {
"type" : "text",
"fields" : {
"keyword" : {
"type" : "keyword",
"ignore_above" : 256
}
}
}
}
},
"settings" : {
"index" : {
"routing" : {
"allocation" : {
"include" : {
"_tier_preference" : "data_content"
}
}
},
"number_of_shards" : "1",
"provided_name" : "trian_index1",
"creation_date" : "1657156271253",
"number_of_replicas" : "1",
"uuid" : "iYRxnx3TTpC51FUzonWV9g",
"version" : {
"created" : "7100199"
}
}
}
}
}

p117
템플릿 우선순위
put index_template/multi_template1
{
"index_patterns":"multi
",
"priority":1,
"template":{
"mappings":{
"properties":{
"age":{"type":"integer"},
"name":{"type":"text"}
}
}
}
}
put index_template/multi_template2
{
"index_patterns":"multi
",
"priority":2,
"template":{
"mappings":{
"properties":{
"name":{"type":"keyword"}
}
}
}
}

put multi-data_index

mysql, oracle

p125

p127 자주 사용되는 분석기
post _analyze
{
"analyzer":"stop",
"text":"The 10 most loving dog breeds."
}
stop(분석기) : simple과 비슷한데, stop(필터, p131참조)이 적용
post _analyze
{
"tokenizer":"uax_url_email",
""filter":["uppercase"]
"text":"email : test@test.com abc"
}
stop 필터 : 불용어(stop words): a, the, you 등등 ...
분석기: 토크나이저 +필터
p128 토크나이저
토크나이저 종류 p127 표 3.10
standard, lowercase, ngram, uax_url_email

put customer_analyzer
{
"settings":{
"analysis":{
"filter":{
"my_stopwords":{
"type":"stop",
"stopwords":["lions"]
}
},
"analyzer":{
"my_analyzer":{
"type":"custom",
"char_filter":[],
"tokenizer":"standard",
"filter":["lowercase","my_stopwords"]
}
}
}
}
}

get customer_analyzer/_analyze
{
"analyzer":"my_analyer",
"text":"Cats Lions Dogs"
}

서버 호스팅 python, flask,

  • 게시판, 카드 결제 기능, 회사용 erp, 기술자용 모듈
    클라우드 워싱

p134
put customer_analyzer2
{
"settings":{
"analysis":{
"filter":{
"my_stopwords":{
"type":"stop",
"stopwords":["lions"]
}
},
"analyzer":{
"my_analyzer":{
"type":"custom",
"char_filter":[],
"tokenizer":"standard",
"filter":["my_stopwords", "lowercase"]
}
}
}
}
}

get customer_analyzer2/_analyze
{
"analyzer":"my_analyzer",
"text":"Cats Lions Dogs"
}

결과
{
"tokens" : [
{
"token" : "cats",
"start_offset" : 0,
"end_offset" : 4,
"type" : "",
"position" : 0
},
{
"token" : "lions",
"start_offset" : 5,
"end_offset" : 10,
"type" : "",
"position" : 1
},
{
"token" : "dogs",
"start_offset" : 11,
"end_offset" : 15,
"type" : "",
"position" : 2
}
]
}

get kibana_sample_data_ecommerce/_search
{
"query":{
"match":{
"category":"clothing"
}
}
}

get kibana_sample_data_ecommerce/_search
{
"query":{
"bool":{
"filter":{
"term":{
"day_of_week":"Friday"
}
}
}
}
}
p137 검색
sql(select), es(query)
sql(like), es(score)
p139
P84 sample 추가

p141
쿼리 스트링: 한 줄 정도 간단한 쿼리
쿼리 DSL(Domain Specific Language):
get kibana_sample_data_ecommerce/_search?q=customer_full_name:Mary

get kibana_sample_data_ecommerce/_search
{
"query":{
"match":{
"customer_full_name": "Mary"
}
}
}

p143 유사도 스코어
get kibana_sample_data_ecommerce/_search
{
"query":{
"match":{
"products.product_name": "Pants"
}
},
"explain":false
}

===================================
get kibana_sample_data_ecommerce/_search
{
"query":{
"match":{
"products.product_name": "Pants"
}
},
"explain":true
}

p145 스코어 알고리즘(BM25)이해하기
스코어:연관성(검색어와 본문에서 찾은 단어)
5.x이전 버전: tf-idf
5.x이후 버전: bm25(tf-idf + 문서 길이)

p147
Term Freq 용어 빈도: 어떤 용어가 하나의 도큐먼트에 얼마나 많이 등장하는지 ...
the, a, is, are 등 상용구: 중요성이 낮음->도큐먼트 프리퀀시가 높을수록 중요한 단어가 아님.

p146
Document Freq 문서 빈도: 어떤 용어가 얼마나 자주 등장하는지?
어떤 단어가 얼마나 많은 문서에서 출현하는가?
inverse document freq(역수): idf가 높으면 특정 문서에서만 보인다는 뜻
->tf-itf가 높으면 특정 문서에서 중요한 단어일 가능성이 높다는 뜻.

p152 매치 쿼리
<customer_full_name에서만 Mary 찾음>
get kibana_sample_data_ecommerce/_search
{
"_source":["customer_full_name"],
"query":{
"match":{
"customer_full_name": "Mary"
}
}
}

<모든 필드에서 MARY 찾음>
get kibana_sample_data_ecommerce/_search
{
"query":{
"match":{
"customer_full_name": "Mary"
}
}
}

<Mary or Bailey 두 개의 검색어로 찾음: 네이버나 구글같은 검색포털>
get kibana_sample_data_ecommerce/_search
{
"_source":["customer_full_name"],
"query":{
"match":{
"customer_full_name": "mary bailey"
}
}
}

<mary and bailey 두 개의 검색어로 검색: 네이버 구글 등 포털>
get kibana_sample_data_ecommerce/_search
{
"_source":["customer_full_name"],
"query":{
"match":{
"customer_full_name": {
"query":"mary bailey",
"operator": "and"}
}
}
}

->엘라스틱에서는 or가 기본 설정값, 구글 등에서는 and

p154
매치 프레이즈 쿼리
get kibana_sample_data_ecommerce/_search
{
"_source":["customer_full_name"],
"query":{
"match_phrase":{
"customer_full_name": "mary bailey"
}
}
}

p155
용어 쿼리:검색어를 토큰으로 나누지 않고 통으로 검색
get kibana_sample_data_ecommerce/_search
{
"_source":["customer_full_name"],
"query":{
"term":{
"customer_full_name": "mary"
}
}
}

p162 범위 쿼리
p163
gte: 10 (10과 같거나 더 큰 값)
gte: 2021-1-21
gt
ite:20(20보다 작거나 같은)
it

get kibana_sample_data_flights/_search
{
"query":{
"range":{
"timestamp":{
"gte":"2022-07-07",
"it":"2022-07-08
}
}
}
}

put range_test_index
{
"mappings":{
"properties":{
"test_date":{
"type":"date_range"
}
}
}
}

get range_test_index

<doc1은 "date_range"에 맞으니까 put잘됨>
put range_test_index/_doc/1
{
"test_date":{
"gte":"2022-07-07",
"lt":"2022-07-08"
}
}

<doc 2 는 "date_range"에 안맞으니까 put 잘 안됌>
put range_test_index/_doc_2
{
"test_date":"2022-07-07"
}

p166
relation에 들어갈 수 있는 값들
intersects(기본): 쿼리 범위와 도큐먼트의 범위가 일부라도 겹치면 된다. 즉 교집합이 있기만 하면 된다.
contains: 도큐먼트의 범위가 쿼리 범위를 포함
within: 도큐먼트의 범위가 쿼리 범위 내에 속해야함

10~19(doc1)
15~ 49(query)
15~19

      20~29( doc2)

15~ 45(query)
20~29()
30~39(doc3)
15~ 45(query)
40~45()

p168 must
p169
get kibana_sample_data_ecommerce/_search
{
"query":{
"bool":{
"must":{
"match":{
"customer_first_name":"mary"
}
}
}
}
}

get kibana_sample_data_ecommerce/_search
{
"query":{
"bool":{
"must":[
{"term":{"day_of_week":"Sunday"}},
{"match":{"customer_first_name":"mary"}}
]
}
}
}

p170: 제외할 검색어
get kibana_sample_data_ecommerce/_search
{
"query":{
"bool":{
"must":{
"match":{
"customer_first_name":"mary"
}
},
"must_not":{
"term":{
"customer_last_name":"bailey"
}
}
}
}
}

should
p172

filter

p177
용어
?용어??
p178
get kibana_sample_data_ecommerce/_search
{
"_source":"customer_full_name",
"query":{
"wildcard": {
"customer_first_name.keyword": "M?r*"
}

}
}

p183
키바나(seaborn, matplotlib + dashboard, geo)

p185
메트릭 집계
avg
min
max
sum

percentiles 백분위
stats min, max, sum, avg, count 한번
cardinality: 행 수; 데이터의 개수
geo-centroid: 위치 정보의 중심(광주 동구, 서구, 남구, 북구 =>시청)

ELK stack: 로그스태시(비트)(분산컴퓨터;(ex)클라우드)로부터 로그데이터 수집) => 엘라스틱 서치(서치엔진->저장소)=>키바나를 통해 시각화

11번가(한국거주인) 서버-고객들

아마존(서버: 미국 여러군데, 일본, 프랑스, 독일, 영국 등등 전세계 각지)
p186

get kibana_sample_data_ecommerce/_search
{
"size":0,
"aggs":{
"stats_aggs":{
"avg":{
"field": "products.base_price"
}
}
}
}

get kibana_sample_data_ecommerce/_search
{
"size":0,
"aggs":{
"stats_aggs":{
"cardinality":{
"field": "products.base_price"
}
}
}
}

get kibana_sample_data_ecommerce/_search
{
"size":0,
"aggs":{
"stats_aggs":{
"cardinality":{
"field": "products.base_price"
, "precision_threshold": 100
}
}
}
}

p189
precision_threshold: 정확도(높으면 리소스 소모가 많다)

p190
get kibana_sample_data_ecommerce/_search
{
"size":0,
"query":{
"term":{
"day_of_week": "Monday"
}
}
,
"aggs":{
"query_aggs":{
"sum":{
"field": "products.base_price"
}
}
}
}

Monday sum: 45457.28125
Tuesday sum: 44876.78125

get kibana_sample_data_ecommerce/_search
{
"size":0,
"aggs":{
"range_aggs":{
"range":{
"field": "products.base_price"
, "ranges": [
{"from":0, "to":50},
{"from":50, "to":100},
{"from":100, "to":200},
{"from":200, "to":1000}
]
}
}
}
}

get kibana_sample_data_ecommerce/_search
{
"size":0,
"aggs":{
"term_aggs":{
"terms":{
"field": "day_of_week"
, "size": 6
}
}
}
}

get kibana_sample_data_ecommerce/_search
{
"size":0,
"aggs":{
"term_aggs":{
"terms":{
"field": "day_of_week"
, "size": 5
},
"aggs":{
"avg_aggs":{
"avg": {
"field": "products.base_price"
}
}
}
}
}
}

profile
반갑습니다

0개의 댓글