뒤로가기

ElasticSearch Query

//전체검색
GET mydoc/_search
{
    "query":{
        "match_all":{ } //전체검색
    },
    "size":30,//노출개수
    "track_total_hits": true, 
    "sort":{
        "device" : "desc" //정렬 
        
    } 
}


/*
index_for_search 인덱스의 fieldForSearch 필드가 text 타입이고
standard analyzer 를 사용한다면 질의어인 “this is something” 
이라는 텍스트는 “this”, “is”, “something” 이라는 3개의 텀으로 분리되어 역색인 검색

match 쿼리는 기본적으로 OR
*/
GET index_for_search/_search
{
  "query": {
    "match": {
      "fieldForSearch": {
        "query": "this is something",
        "operator": "and"
      }
    }
  }
}

//term 쿼리는 지정한 필드가 질의어와 정확히 일치하는 문서를 찾는 쿼리
GET index_for_search/_search
{
  "query": {
    "term": {
      "fieldForSearch": {
        "value": "Hello"
      }
    }
  }
}

//aggregation, sorting, scripting 사용하기위해서는 fielddata : true 설정해야됨 
//doc_values를 권장한다고 하니 찾아봐야겠음. 
PUT mydoc/_mapping
{
  "properties": {
    "p_num": { 
      "type":     "text",
      "fielddata": true
    }
  }
}

POST mydoc/_search
{
  "query":{
    "bool":{
      "filter":[ 
        {"range":{"date":{"gte":"2024-04-08","lte":"2024-04-09"}}} //날짜검색
      ]
    }
  },
  "size" : 0,
  "aggs": {
      "aggs_stats" : {
        "date_histogram" : { //날짜로 group by 
          "field": "date",
          "calendar_interval": "day",
          "min_doc_count" : 0
      }
    }
  }
}


POST /mydoc/_search
{
  "query":{
    "bool":{
      "filter":[
          { "range":{"date":{"gte":"2024-04-08","lte":"2024-04-09"}
            
          } 
        }
      ]
    }
  },
  "aggs": {
    "aggs_stats": {
      "date_histogram": {
        "field": "date",
        "calendar_interval": "day",
        "format": "yyyy-MM-dd", 
        "min_doc_count" : 0
      }
      ,"aggs": { 
        "aggs_page": {
          "terms": { //문자열 group by 
            "field": "p_num"
            //배열로 여러개 검색도됨 
						            [
                        	"1111",
                            "2222",
                            "3333",
                            "4444"
                        ]
          }
        }
      }
    }
  }
}

//다음찾기 
//정렬에 나온 키값으로 search_after으로 조회 
POST monfood_search/_search/
{
    "search_after": ["1712793600000"]
    ,"sort" : [
      {
        "date" : {
          "order" : "asc"
        }
      }
    ]
}

// \" 로 감싸주면 띄어쓰기 포함한 정확값 
post monfood_order_v2/_search
{

  "query": {
    "query_string": {
      "default_field": "order_num",
      "query": "\"20240424-21315287\""
    }
  }
}

like 검색 *검색어*

ElasticSearch Index 여러개(_msearch)

//인덱스 여러개 조회하기 
POST /_msearch
{"index":"monfood_product_click,monfood_search"}
{"query" :{"match_all" : {}}, "from":0, "size":2}

{"index":"monfood_product_click"}
{"query" : {"bool":{ "filter":[{"range":{"date":{"gte":"2024-04-08","lte":"2024-04-09"}}}]}}, "from":0, "size":2}
{"index":"monfood_search"}
{"query" : {"match_all" : {}}, "from":0, "size":2}

Elastic doc_values

/*
doc_values
역색인 구조를 사용하면 검색어를 고유한 정렬된 키워드 목록에서 검색할 수 있으며, 검색어를 목록에 즉시 접근할 수 있다.
_source와 동일한 값을 저장하지만 정렬 및 집계에서 훨씬 더 효율적인 컬럼 지향 방식으로 저장한다. 
*/

PUT mydoc/_mapping
{
  "properties": {
    "p_num": { 
      "type":     "text",
      "doc_values": false // default : true
    }
  }
}

기타

{
    "took": "검색하는데 걸린 시간(ms)",
    "timed_out": "시간 초과 여부 (true/false)",
    "_shards": {
        "total": "검색한 shard 수",
        "successful": "검색에 성공한 shard 수",
        "skipped": 0,
        "failed": "검색에 실패한 shard 수"
    },
    "hits" : {
        "total": "검색 된 문서의 총 개수",
        "max_score": "검색 조건과 일치한 점수의 최대 값",
        "hits" : [
            {
                "_index": "인덱스 이름",
                "_type": "_doc", # 7.x부터 _doc으로 통일,
                "_id": "id",
                "_score": "해당 document가 검색 쿼리와 일치하는 상대적인 값",
                "_source": {
                    # 데이터
                }
            }
        ]
    }
}

must: bool must 절에 지정된 모든 쿼리가 일치하는 document 조회
must_not: bool must_not 절에 지정된 모든 쿼리가 일치하지 않는 document 조회
should: bool should 절에 지정된 모든 쿼리 중 하나라도 일치하는 document 조회
filter: filter절에 지정된 모든 쿼리와 일치하는 documnet를 조회 (score 무시)

gte (Greater-than or equal to) - 이상 (같거나 큼)
gt (Greater-than) – 초과 (큼)
lte (Less-than or equal to) - 이하 (같거나 작음)
lt (Less-than) - 미만 (작음)

집계하기 aggs 
{
    "query": {
        "term": {
            "address": "street"
        }
    },
    "aggs": {
        "balance_avg": { # response 에 명시할 통계 결과 필드명
            "avg" : { # 집계 타입 (sum, 등)
                "field" : "balance" # 어떤 필드를 통계 낼 것인지
            }
        }
    }
}