|
ITWeb/개발일반 2016. 7. 21. 10:12
elasticsearch에서 문서 데이터를 처리 하다 보니 json format을 많이 사용하게 됩니다. 그래서 색인을 위한 데이터중 일부는 mysql 에 json 형태로 저장할 필요가 있는데요. mysql 5.7 부터 data type 으로 json 을 지원하고 있습니다.
참고문서) https://dev.mysql.com/doc/refman/5.7/en/json.html https://dev.mysql.com/doc/refman/5.7/en/json-function-reference.html
선언) CREATE TABLE XXXX ( seq BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, doc JSON NOT NULL, PRIMARY KEY (seq) ) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci;
등록) INSERT INTO XXXX(doc) VALUE (?)
조회)
JDBC) # 등록 PrepareStatement.setObject(1, OBJECT);
# 조회 ResultSet.getObjecrt(1, "doc"); - JDBC 를 통해 DB 에 등록 할 때 value 값에 대한 Object를 Array 인지 Object 인지 확인해서 넣어 주어야 값이 원하는 형태로 저장 됩니다.
Elasticsearch Mapping) "FIELD_NAME": { "type":"object", "enabled":false }
Elastic/Elasticsearch 2016. 6. 28. 09:53
몇 가지 눈에 들어 오는게 있어서 scrap 합니다.
[원문] https://www.elastic.co/blog/this-week-in-elasticsearch-and-apache-lucene-2016-06-27
[요점] - low-level Java REST client has landed. 별도의 http client 를 이용해서 만들지 않고 es 에서 제공하는거 사용하면 될 것 같습니다.
- index.store.preload warmmer 기능이 이걸로 대체 되는 것 같습니다.
- no longer turns red when creating an index 순간 red 나올 때가 있었는데 false alarm 이 줄어 들겠내요.
- default similarity is now BM25 TF/IDF 에서 BM25로 넘어 가는 군요.
- wait for status yellow yellow 도 간혹 발생을 하는데 앞으로 status 에 대해서 다시 점검을 해야 겠내요.
Elasticsearch CoreChanges in 2.x: Changes in master:
- The low-level Java REST client has landed. It is functionally equivalent to the REST clients available in other languages.
- The `index.store.preload` setting can preload the specified Lucene files (eg doc values, norms) into MMAP before a segment comes online. This completes the replacement of warmers.
- The cluster health no longer turns red when creating an index, unless there is a problem assigning shards.
- The default similarity is now BM25.
- The `_timestamp` and `_ttl` fields will not be supported on indices created in 5.x.
- The `fields` parameter has been removed in favour of `stored_fields`, `docvalue_fields` and (for `text` fields only)`fielddata_fields`.
- Some percolator queries don't need in-memory validation to ensure that they match.
- Painless now has capturing lambdas, supports adding static methods like `each` to whitelisted classes, has syntax for initialising arrays, lists and maps,
- Nested inner hits no longer return _index, _type, and _id, and parent/child inner hits doesn't return _index.
- `string` fields weren't upgraded to `text`/`keyword` if `include_in_all` was specified.
- Getting a task with wait_for_completion will return the task result.
- Nodes info returns the calculated size of the total indexing buffer.
- Analysis factories are now MultiTermAware, which will help to remove the lowercase_expanded_terms from the query string query, and to support keyword analyzers on the `keyword` field.
- JNA is now a required dependency.
- Guice has been removed from the script service,
Ongoing changes:
Apache Lucene
Elastic/Elasticsearch 2016. 6. 20. 18:09
aggregation 을 많이 사용하시는 분들은 잘 아실것 같구요. 그냥 기본만 사용하시는 분들에게는 생소할 수 있어서 그냥 정리해 봤습니다.
참고문서) https://www.elastic.co/guide/en/elasticsearch/reference/2.3/search-aggregations.html#_structuring_aggregations
"aggregations" : {
"<aggregation_name>" : {
"<aggregation_type>" : {
<aggregation_body>
}
[,"meta" : { [<meta_data_body>] } ]?
[,"aggregations" : { [<sub_aggregation>]+ } ]?
}
[,"<aggregation_name_2>" : { ... } ]* }
여기서 "<aggregation_name>" 에 대한 내용입니다. 이 값은 기본적으로 aggs 수행 후 return 될 때 사용되는 변수명을 지정하게 됩니다. 간혹 aggregation_name 에 field 명을 주시는 경우가 있을 수 있는데요. 안되는 것은 아니지만 해당 변수에 대한 정확한 용도를 알고 사용하시면 더 좋겠다 싶어서 글 남겨 봤습니다.
/** * Constructs a new aggregation builder. * * @param name The aggregation name * @param type The aggregation type */ public AggregationBuilder(String name, Type type) { if (name == null) { throw new IllegalArgumentException("[name] must not be null: [" + name + "]"); } if (type == null) { throw new IllegalArgumentException("[type] must not be null: [" + name + "]"); } this.name = name; this.type = type; }
...중략...
@Override public final XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(name);
if (this.metaData != null) { builder.field("meta", this.metaData); } builder.field(type.name()); internalXContent(builder, params);
if (factoriesBuilder != null && (factoriesBuilder.count()) > 0) { builder.field("aggregations"); factoriesBuilder.toXContent(builder, params);
}
return builder.endObject(); }
소스 코드를 보셔도 아시겠죠? XContentBuilder 에서 최상위 object name 에 aggregation_name 값을 지정하고 있습니다.
그냥 제가 기억하기 위해 글 남기고 마무리 하겠습니다.
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" } } ] } } }'
Elastic/Elasticsearch 2016. 4. 26. 15:48
이번 weekly 에서 눈에 확 들어 오는건 개인적으로 아래 두 가지 입니다.
원본 글) https://www.elastic.co/blog/this-week-in-elasticsearch-and-apache-lucene-2016-04-25
Elasticsearch CoreChanges in 2.x:
Changes in master:
Ongoing changes:
Elastic/Elasticsearch 2016. 4. 26. 15:18
준비 작업을 조금 해야 할 것 같아서 일단 짧게 기록 합니다.
Elastic Stack 5.0이 정식 릴리즈 되게 되면 Lucene 6.x 기반으로 버전이 올라가게 됩니다. 이에 따라 아리랑 형태소 분석기도 버전을 올려야 하는데요.
일단 올려 보니 에러는 한 군데 보입니다. abstract 로 선언된 method 하나만 구현해 주면 될 것으로 보입니다.
MophemeAttributeImpl.java 파일에 reflectWith(....) 메서드만 구현해 주세요. @Override public void reflectWith(AttributeReflector reflector) { reflector.reflect(MorphemeAttribute.class, "token", koreanToken); } 해당 코드에 대한 검증 작업은 하지 않았으니 사용이나 판단은 각자 알아서 하는 것으로 하겠습니다.
Elastic/Elasticsearch 2016. 4. 22. 17:59
뭐 이런게 고려 사항 일까 싶지만 그냥 머리 식히기 위해서 작성해 봅니다.
synonyms 는 기본적으로 search 시와 index 시에 다 사용이 가능 합니다. 이 둘 사이에 장단점은 아래 링크를 참고해 주시면 좋겠습니다.
참고링크) https://www.elastic.co/guide/en/elasticsearch/guide/2.x/synonyms-expand-or-contract.html
search 시 synonyms 를 적용하기 위해서는 match query 종류를 사용하셔야 합니다. 간혹 term query 종류를 사용하시면서 왜 안되지 하시는 분들도 있는데 주의 하셔야 합니다.
index 시 synonyms 를 적용하기 위해서는 synonyms filter 우선순위를 잘 확인 하셔야 합니다. 제일 앞에 있는 filter 때문에 적용이 안될 수도 있으니 주의 하셔야 합니다. 이 경우 search 시 term query 류를 사용하면 안되던 것이 지원이 되기 때문에 요건에 따라 선택해서 사용하시면 좋을 것 같습니다.
Elastic/Elasticsearch 2016. 4. 22. 11:42
아주 기본적인 내용인데 간혹 놓치고 가는 경우가 있어서 기록해 봅니다. 저 같은 경우는 synonyms 적용하면서 당연히 적용된 줄 알고 테스트 하다 삽질한 경우 입니다.
analyzer 구성은 잘 아시겠지만 settings 에서 수행하게 됩니다. 그리고 설정한 analyzer 를 mappings 에서 사용을 하게 되구요.
설정 방법에 대해서는 아래 문서 참고 하시기 바랍니다.
참고문서) https://www.elastic.co/guide/en/elasticsearch/reference/2.3/analysis.html
참고문서 내 설정 예시) index :
analysis :
analyzer :
standard :
type : standard
stopwords : [stop1, stop2]
myAnalyzer1 :
type : standard
stopwords : [stop1, stop2, stop3]
max_token_length : 500
# configure a custom analyzer which is
# exactly like the default standard analyzer
myAnalyzer2 :
tokenizer : standard
filter : [standard, lowercase, stop]
tokenizer :
myTokenizer1 :
type : standard
max_token_length : 900
myTokenizer2 :
type : keyword
buffer_size : 512
filter :
myTokenFilter1 :
type : stop
stopwords : [stop1, stop2, stop3, stop4]
myTokenFilter2 :
type : length
min : 0
max : 2000
위 예시를 가지고 설명을 드리면, myAnalyzer2 설정에 filter : [standard, lowercase, stop] 으로 정의가 되어 있습니다. 즉, filter 적용 순서가 1. standard 2. lowercase 3. stop 으로 적용이 된다고 보시면 됩니다.
아주 간단하죠. 제가 설정 순서를 잘못해 놓고 왜 안되지 하고 있었습니다. ㅡ.ㅡ;
Elastic/Kibana 2016. 4. 14. 18:10
참 별것도 아닌데 이런것 가지고 삽질 하면 스트레스 받습니다. 그래서 잊지 않기 위해 기록합니다.
보통 elasticsearch 구성 시 default 값을 많이 사용하게 됩니다. 그러다 보니 에러를 자연스럽게 피해가게 됩니다. 뭔소리냐면, refresh_interval 의 경우 default 1s 로 되어 있습니다.
그렇기 때문에 create index 와 create document 를 했을 때 바로 처리가 되는데요. 저 같은 경우는 refresh_interval 을 서비스 특성에 맞춰 변경을 하였습니다. 이로 인해 kibana 설치 및 실행 시 아래와 같은 에러가 발생을 했습니다.
[error][status][plugin:elasticsearch] Status changed from green to red - [document_already_exists_exception] [config][4.5.0]: document already exists, with: {"shard":"0","index":".kibana"}
그래서 이상하다 싶어 .kibana 를 지워주기도 하고 실제 .kibana/config/4.5.0 문서도 지우기도 했는데요. 역시 해결이 안되었습니다. 원인을 refresh_interval 에 있었던 것이죠.
kibana 에서 이건 기본적으로 해당 .kibana 인덱스 생성 시 자동으로 .kibana index settings 에 refresh_interval 을 1s로 해주면 별 문제가 없을 것 같은데.. issue에도 올라와 있는 내용인데 뭐 언젠가 해결해 주겠죠.
이상 마칩니다.
Elastic/Elasticsearch 2016. 4. 12. 09:59
봐야지 봐야지 하다 이제 봅니다. 제 눈에 띄는 것은
- Now that we have removed the percolator API, we should also remove the percolator type and use percolator fieldsinstead.
예전에 분리 되어 있던걸 합치더니 다시 분리 하는 것 같습니다.
task cancelled 기능을 테스트 해봐야 할 것 같습니다.
이제 field name 작성시 주의해야 겠내요. 좀 더 strict 해졌다고 봐야겠죠. ^^ - 아래 코드가 true에서 false로 되었습니다. (이 기능이 성능이나 기타 다른 기능적인 오류를 만들어 내는 걸까요?) jsonFactory.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
percolator 기능이 fields 로 빠졌내요. 이것도 기능 확인을 해봐야 겠내요. 등록된 issue 를 보면 ㅎㅎ 직관적이고 사용이 좀 더 편해진것 같습니다.
core 2.x에 반영된 내용은 거의 v5.0.0 에 적용 될것 같습니다.
루씬은 일단 6.0.0 이 릴리즈 vote 중이였고 이미 4월 8일에 릴리즈 되었습니다. 이외 다른 내용들은 거의 geo point, locaiton 관련 내용들 입니다.
루씬 6.0.0 릴리즈 소식으로는 Java 8 is the minimum Java version required. Dimensional points, replacing legacy numeric fields, provides fast and space-efficient support for both single- and multi-dimension range and shape filtering. This includes numeric (int, float, long, double), InetAddress, BigInteger and binary range filtering, as well as geo-spatial shape search over indexed 2D LatLonPoints. See this blog post for details. Dependent classes and modules (e.g., MemoryIndex, Spatial Strategies, Join module) have been refactored to use new point types. Lucene classification module now works on Lucene Documents using a KNearestNeighborClassifier or SimpleNaiveBayesClassifier. The spatial module no longer depends on third-party libraries. Previous spatial classes have been moved to a new spatial-extras module. Spatial4j has been updated to a new 0.6 version hosted by locationtech. TermsQuery performance boost by a more aggressive default query caching policy. IndexSearcher's default Similarity is now changed to BM25Similarity. Easier method of defining custom CharTokenizer instances.
원본링크) Elasticsearch CoreChanges in 2.x: Changes in master: Ongoing changes: Apache Lucene
|