'query'에 해당되는 글 18건

  1. 2022.01.28 [Elasticsearch] Exists Query...
  2. 2021.10.27 [Elasticsearch] Term vs Terms Query
  3. 2020.03.13 [AWS] aws cli 사용 시 --query 알아보기
  4. 2018.07.03 [Elasticsearch] Nested Query 는 Script Fields 를 지원 하지 않습니다.
  5. 2018.04.12 [Elasticsearch] WildcardQuery 알아보기
  6. 2017.12.20 [Elasticsearch] simple query 내 synonym graph 사용
  7. 2017.01.02 [Elasticsearch] Range Query From, To 포함 여부.
  8. 2016.10.18 [Range Query] datetime query 작성 예제.
  9. 2016.05.24 [Elasticsearch] BoolQueryBuilder + TermsQueryBuilder 사용 시 minimum_should_match와 min_should_match
  10. 2015.12.15 [Elasticsearch - The Definitive Guide] Phrase Matching

[Elasticsearch] Exists Query...

Elastic/Elasticsearch 2022. 1. 28. 11:44

공식 문서)

Exists query | Elasticsearch Guide [7.16] | Elastic

 

exists query 는 field 자체가 아래 이유등으로 인해 생성 되자 않는 문서를 찾습니다.

즉, 

- null 또는 empty array (빈문자열 "" 은 해당 되지 않습니다.)

- index: false

- ignore_above 설정 값을 넘었을 때

- ignore_malformed 설정에 걸렸을 때

 

검색 엔진 특성상 null, empty string 에 대해서는 전처리를 통해서 명확히 제거 하거나 목적에 맞게 변형 하는 것이 좋습니다.

 

검색엔진을 이용해서 field:"" 또는 field: " " 과 같은 질의를 작성 하는 것은 좋지 않습니다.

 

:

[Elasticsearch] Term vs Terms Query

Elastic/Elasticsearch 2021. 10. 27. 16:14

보셔야 하는 클래스는

- TermQueryBuilder

- TermsQueryBuilder

입니다.

 

두 Query 의 큰 차이는 단독으로 사용 되었을 때 Scoring 이 어떻게 되느냐 인데요.

Term 은 Score 계산이 되어서 나오고 Terms 는 Constant Score Query 처럼 1.0 으로 나온다는 것입니다.

 

코드를 좀 더 따라 가다 보면 

- MapperFieldType

클래스 내 Query API 들에 대한 Interface 나 Implement 코드를 확인해 보실 수 있습니다.

 

아래는 Terms Query 에 대한 코드를 가져온 내용입니다.

    /** Build a constant-scoring query that matches all values. The default implementation uses a
     * {@link ConstantScoreQuery} around a {@link BooleanQuery} whose {@link Occur#SHOULD} clauses
     * are generated with {@link #termQuery}. */
    public Query termsQuery(Collection<?> values, @Nullable SearchExecutionContext context) {
        BooleanQuery.Builder builder = new BooleanQuery.Builder();
        for (Object value : values) {
            builder.add(termQuery(value, context), Occur.SHOULD);
        }
        return new ConstantScoreQuery(builder.build());
    }

뭐 혼자 기억 하기 위한 기록 이라서 이 정도까지만 기록해 두겠습니다.

 

:

[AWS] aws cli 사용 시 --query 알아보기

Cloud&Container/AWS 2020. 3. 13. 21:46

알아 보기라고 하기에는 그냥 약간의 예제와 학습 해야 하는 문서 링크 입니다.

 

https://jmespath.org/specification.html#filter-expressions

$ aws iot list-thing-types --query 'thingTypes[].[thingTypeName, thingTypeName==`1584075120782`]'
$ aws iot list-thing-types --query "thingTypes[].[thingTypeName, starts_with(thingTypeName, '15840')]"

 

JMES 가 이거 만든 사람 이름의 약어 인것 같은데, 맞는지 모르겠네요.

© Copyright 2014-2015, James Saryerwinnie.

 

그리고 이 분 AWS 직원인 것 같습니다. :)

:

[Elasticsearch] Nested Query 는 Script Fields 를 지원 하지 않습니다.

Elastic/Elasticsearch 2018. 7. 3. 08:38

안되는 기능입니다.,


{

  "error": {

    "root_cause": [

      {

        "type": "parsing_exception",

        "reason": "[nested] query does not support [script_fields]",

        "line": 22,

        "col": 31

      }

    ],

    "type": "parsing_exception",

    "reason": "[nested] query does not support [script_fields]",

    "line": 22,

    "col": 31

  },

  "status": 400

}


:

[Elasticsearch] WildcardQuery 알아보기

Elastic/Elasticsearch 2018. 4. 12. 15:46

참고문서)

https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-wildcard-query.html


WildcardQuery 는 사실 추천 하지 않지만 필요에 따라 사용해야 할 수도 있습니다.

성능적으로 좋은 API 는 아니기 때문에 추천 하지 않는 것이지 기능적으로는 유용할 수도 있습니다.


[Field Type]

Keyword : not_analyzed

Text(String) : analyzed


[Lucene]

WildcardQuery -> MultiTermQuery


[Elasticsearch]

WildcardQueryBuilder


[Usage]

WildcardQuery 는 기본적으로 field type 의 색인 속성과는 상관 없습니다.

not_analyzed field 에 대해서 질의 할 때와 analyzed field 에 대해서 질의 할 때 조금 모호 할 수 있습니다.

즉, term query 를 사용하기 때문에 아래와 같이 예를 들겠습니다.

Field name : title

Text value : nike clothes


Case 1)

not_analyzed field)

term : nike clothes


"query" : {

"wildcard" : {

"title" : "ni*e"

}

}


not matched


결과가 나오지 않는 이유는 추출된 term 이 "nike clothes" 이기 때문에 "ni*e" 로 했을 경우 추출 텀의 제일 마지막 문자가 e 가 아니기 때문에 매칭이 되지 않은 것입니다.

매칭이 되게 하려면 "ni*" 또는 "ni*s" 로 해야 매칭이 됩니다.


Case 2)

analyzed field)

terms : [nike, clothes]


"query" : {

"wildcard" : {

"title" : "ni*e"

}

}


matched


이 경우는 추출된 term 이 두 개 이며, nike 라는 텀에 대해서 매칭이 된 것입니다.



:

[Elasticsearch] simple query 내 synonym graph 사용

Elastic/Elasticsearch 2017. 12. 20. 10:11

일단 나중에 잊을 수도 있어서 keep 합니다.


Ref.

https://www.elastic.co/guide/en/elasticsearch/reference/6.1/query-dsl-simple-query-string-query.html#_synonyms_2


Simple Query 사용 시 추가 되는 parameter 인데, 이 기능을 잘 활용하면  query expansion (query rewrite) 기능을 대체 할 수도 있겠다는 생각이 듭니다.

그래서 일단 기록!

Synonyms

The simple_query_string query supports multi-terms synonym expansion with the synonym_graph token filter. When this filter is used, the parser creates a phrase query for each multi-terms synonyms. For example, the following synonym: "ny, new york" would produce:


(ny OR ("new york"))


It is also possible to match multi terms synonyms with conjunctions instead:

GET /_search

{

   "query": {

       "simple_query_string" : {

           "query" : "ny city",

           "auto_generate_synonyms_phrase_query" : false

       }

   }

}

약간의 부연 설명을 하자면, 보통 사용자가 입력한 검색어만 가지고 검색을 하는 경우는 이커머스에서는 거의 없습니다.

대부분 사용자가 입력한 검색어 + 확장검색어 형태로 질의를 하게 되는데요.

일반적으로 가장 많이 사용하는 방식이 색인 시점에 동의어를 통한 검색어 확장입니다.

이건 색인 시점이고 위 기능을 잘 활용하게 되면 질의 시점에 검색어 확장을 통한 상품 매칭을 할 수 있습니다.

저는 보통 Query Expansion 기능이라고 부르는데요. 이 작업은 Query Rewriter 라고 불리는 영역에서도 수행이 되기도 합니다.


간단한 예를 들자면)

"나이키" 라는 검색어가 들어 왔을 때 이를 개인화 query expansion 기능을 적용 한다면 저 키워드를 입력한 사용자가 선호 하는게 "운동화" 였다면, 실제 검색 매칭에 사용되는 검색어는 "나이키" + "운동화" 가 되는 것입니다.

이건 단순 예시 입니다.

:

[Elasticsearch] Range Query From, To 포함 여부.

Elastic/Elasticsearch 2017. 1. 2. 12:44

도대체 왜 맨날 잊어버리는지 모르겠지만, 기억력 회복을 위해 기록해 봅니다.


Range query  사용 시 from, to, gt, gte, lt, lte parameter 를 사용 합니다.

RangeQueryBuilder.java 소스코드를 보면 아래와 같이 정의가 되어 있습니다.


private final String name;
private Object from;
private Object to;
private String timeZone;
private boolean includeLower = true;
private boolean includeUpper = true;
private float boost = -1;
private String queryName;
private String format;


기본적으로 lower, upper 값을 포함하게 되어 있습니다.

그러므로, from, to 는 값을 포함 하게 됩니다.

MySQL 에서 제공하고 있는 BETWEEN min AND max 도 min 과 max 값을 포함 하고 있는 것 처럼 동일 합니다.


:

[Range Query] datetime query 작성 예제.

Elastic/Elasticsearch 2016. 10. 18. 11:15

늘 그렇듯이 기억력의 한계 극복을 위해 기록합니다.


              "range": {
                "time": {
                  "gte": "2016-10-17 00:00:00.000",
                  "lte": "2016-10-17 23:59:59.999",
                  "format": "yyyy-MM-dd HH:mm:ss.SSS",
                  "time_zone": "+09:00"
                }
              }


보시면 다들 아시는 내용입니다.


[참고문서]

https://www.elastic.co/guide/en/elasticsearch/reference/2.4/query-dsl-range-query.html

https://www.elastic.co/guide/en/elasticsearch/reference/2.4/mapping-date-format.html

https://www.elastic.co/guide/en/elasticsearch/reference/2.4/date.html

:

[Elasticsearch] BoolQueryBuilder + TermsQueryBuilder 사용 시 minimum_should_match와 min_should_match

Elastic/Elasticsearch 2016. 5. 24. 18:11

이게 또 언제 변수명이 바뀌었을까요?

버전 릴리즈 될때마다 소스코드를 다 따라 갈수가 없다 보니 이런 오류를 경험하게 되내요.


주의) min_should_match 는 java api 를 이용해서는 사용 할 수 없습니다.


[Terms Query]

이 쿼리는 field 에 여러개의 term 을 넣어서 질의 할 수 있도록 해줍니다.

그래서 기본 or 검색을 지원하고 있구요. 여기서 and 연산을 하고 싶으면 terms query 에 아래 변수 값을 지정 하셔야 합니다.


min_should_match:TERM_SIZE


OR)

curl -XGET "http://localhost:9200/_search?pretty" -d'

{

    "size": 10,

    "query" : {

        "terms": {

           "title": [

              "포니",

              "이펙트"

           ],

           "min_should_match": 1

        }                

    }

}'



AND)

curl -XGET "http://localhost:9200/_search?pretty" -d'

{

    "size": 10,

    "query" : {

        "terms": {

           "title": [

              "포니",

              "이펙트"

           ],

           "min_should_match": 2

        }                

    }

}'


[Bool Query + Terms Query]

이 쿼리는 compound query 작성을 위해 많이 사용하는 것입니다.

bool query 안에 terms query 를 섞어 사용하는 것이구요. 좀 더 and, or 연산을 다양하게 할 수 있게 해줍니다.

여기서는 miminum_should_match 를 통해서 and, or 연산을 해야 하는데 terms query 에서의 min_should_match 를 사용하지 않게 되면 정상적인 결과를 얻을 수 없게 됩니다. (아무래도 2.3.3 에서 5.0 으로 넘어가는 과도기라 그런게 아닌가 싶습니다.)

should 를 여러개 사용할 경우 miminum_should_match 설정을 하셔야 합니다.


OR)

curl -XGET "http://localhost:9200/_search?pretty" -d'

{

    "size": 10,

    "query" : {

        "bool" : {

            "should": [

               {

                   "terms": {

                      "title": [

                         "포니",

                         "이펙트"

                      ],

                      "min_should_match": "1"

                   }

               }

            ]

        }

    }

}'


AND)

curl -XGET "http://localhost:9200/_search?pretty" -d'

{

    "size": 10,

    "query" : {

        "bool" : {

            "should": [

               {

                   "terms": {

                      "title": [

                         "포니",

                         "이펙트"

                      ],

                      "min_should_match": "2"

                   }

               }

            ]

        }

    }

}'


:

[Elasticsearch - The Definitive Guide] Phrase Matching

Elastic/TheDefinitiveGuide 2015. 12. 15. 11:20

match query type 중 phrase 에 대한 이해를 돕기 위해 기록 합니다.


원문링크)

https://www.elastic.co/guide/en/elasticsearch/guide/current/phrase-matching.html


원문 Snippet)

What Is a Phraseedit

For a document to be considered a match for the phrase “quick brown fox,” the following must be true:

  • quick, brown, and fox must all appear in the field.
  • The position of brown must be 1 greater than the position of quick.
  • The position of fox must be 2 greater than the position of quick.

If any of these conditions is not met, the document is not considered a match.

Tip

Internally, the match_phrase query uses the low-level span query family to do position-aware matching. Span queries are term-level queries, so they have no analysis phase; they search for the exact term specified.

Thankfully, most people never need to use the span queries directly, as the match_phrasequery is usually good enough. However, certain specialized fields, like patent searches, use these low-level queries to perform very specific, carefully constructed positional searches.

다시 한번 정리 하면,

position-aware matching 을 이용하는 span query

- 첫번째 term 에 대한 position에 의해 나머지 term 들의 matching position 은 quick의 position 보다 커야 합니다.

: