Annotation
# title: Annotation date: 2022-06-21 11:08:44 permalink: /pages/v1.x/5d5c6e/
This article will introduce the detailed explanation of the related classes of the Easy-Es annotation package (for more detailed description, please click to view the source code annotation)
Annotation package source code: 👉 easy-es-annotation (opens new window)
# @EsMapperScan (opens new window)
Description: mapper scan annotation, the function is consistent with MP's @MapperScan
Use location: Springboot startup class
@EsMapperScan("cn.easy-es-mapper")
public class Application{
// omit other...
}
2
3
4
property | type | must specify | default value | description |
---|---|---|---|---|
value | String | is | "" | full path of the package where the custom mapper is located |
Tips
Since both EE and MP scan Mapper using Springboot's doScan, and the two systems are independent of each other, there is no way to isolate each other during scanning, so if your project uses both EE and MP, you need to use EE's Mapper Put it in a different package from MP's Mapper, otherwise the project will not start normally.
# @Settings (opens new window)
- Description: Index Settings information annotation, which can set the Settings information in the ES index.
-Usage location: entity class
@Settings(shardsNum = 3, replicasNum = 2, settingsProvider = MySettingsProvider.class)
public class Document {
// Omit other fields
}
2
3
4
Properties | Type | Required | Default | Description |
---|---|---|---|---|
shardsNum | Int | No | 1 | Number of index shards, the default value is 1 |
replicasNum | Int | No | 1 | Number of index replicas, the default value is 1 |
maxResultWindow | Int | No | 10000 | Default maximum number of returns |
refreshInterval | String | No | "" | Index refresh interval es default value is 1s ms: represents milliseconds s: represents seconds m: represents minutes |
settingsProvider | Class | No | DefaultSettingsProvider.class | Custom settings provider class. The default is DefaultSettingsProvider empty implementation. If you want to customize it, you can inherit this class and override the getSettings method. Return settings information as Map |
Warm reminder
- maxResultWindow: The default maximum number of returns, the default value is 10000. If it exceeds this value, it is recommended to use searchAfter or rolling query, etc., for better performance. For details, please see the expansion function chapter. When this value is adjusted to greater than 1W, the index needs to be updated and turned on synchronously. Enable-track-total-hits=true in the configuration file can take effect
- settingsProvider: Custom settings provider class. When in a small number of scenarios, these parameters built into the framework are not enough to meet your settings for index Settings, you can customize the class and inherit DefaultSettingsProvider, override the getSettings method, and configure your own settings. The defined settings information is returned as a Map. In this way, all Settings supported by ES can be supported.
# @IndexName (opens new window)
- Description: Index name annotation, identifying the index corresponding to the entity class. Corresponding to MP's @TableName annotation, this annotation was @TableName before v0.9.40.
-Usage location: entity class
@IndexName
public class Document {
// Omit other fields
}
2
3
4
Property | Type | Required | Default value | Description |
---|---|---|---|---|
value | String | No | "" | Index name, which can be simply understood as the MySQL table name |
aliasName | String | No | "" | Index alias |
keepGlobalPrefix | boolean | No | false | Whether to keep using the global tablePrefix value is consistent with MP usage |
refreshPolicy | Enum | No | NONE | Index data refresh policy, the default is no refresh, its value refers to the RefreshPolicy enumeration class, there are 3 refresh strategies |
Dynamic index name support If your index name is not fixed, we provide two ways to modify the index name in CRUD
- Call the mapper.setCurrentActiveIndex(String indexName) method. The mapper here is your customized mapper, such as documentMapper. After modifying the index name through this API, it will take effect globally.
- Specify the index used by the current operation in the corresponding parameter, such as wrapper.index(String indexName). After modifying the index name through this API, it will only affect the operation corresponding to the wrapper, with the finest granularity.
Warm reminder
- When you want to use the class name directly as the index name and do not need to configure other indexes, you can omit this annotation
- The index name specified by annotation has the highest priority. If an annotation index is specified, the global configuration and automatically generated index will not take effect, and the index name specified in the annotation will be used. Priority sorting: Annotation index > Global configuration index prefix > Automatic generation
- keepGlobalPrefix option, (only supported in version 0.9.4+), the default value is false, whether to keep using the global indexPrefix value:
- This annotation option will only take effect when the global tablePrefix, @TableName annotation and value are specified. If its value is true, the final index name used by the framework is: global indexPrefix + the value of this annotation, for example: dev_document
- The usage of this annotation option is consistent with MP.
- RefreshPolicy data refresh strategy
- None does not refresh, the default strategy of es. Under this strategy, there will be a certain delay before the data changes take effect, but the writing performance is the best. Under normal circumstances, this default strategy can be used.
- IMMEDIATE refreshes immediately, suitable for business scenarios sensitive to data delay, but consumes the most system resources
- WAIT_UNTIL After requesting to submit the data, wait for the data to be refreshed (about 1s) before ending the request. The performance loss is moderate and it is a compromise solution.
# @IndexId (opens new window)
- Description: ES primary key annotation,Before v0.9.40 this annotation was @TableId.
- Use location: The field used as the ES primary key in the entity class corresponds to the @TableId annotation of MP
public class Document {
@IndexId
private String id;
// omit other fields
}
2
3
4
5
property | type | must specify | default value | description |
---|---|---|---|---|
type | Enum | No | IdType.NONE | Specify the primary key type |
Tips
- When your field is named id and the type is String, and you do not need to use UUID and custom ID type, you can omit this annotation
- Because es has processed the default name of id (underscore+id):_id, EE has blocked this step for you, you do not need to specify it in the annotation, and the framework will automatically complete the mapping for you.
- Id generation type supports the following:
- IdType.NONE: is automatically generated by ES and is the default configuration, no additional configuration is required. Recommended
- IdType.UUID: System generates UUID, and then inserts into ES (not recommended)
- IdType.CUSTOMIZE: is defined by the user, the user sets the id value by himself, if the id specified by the user does not exist in es, a new record will be added when inserting, if the id specified by the user is in If a record already exists in es, the record corresponding to the id is automatically updated.
Priority: Annotation-configured Id generation strategy > Globally configured Id generation strategy
# @IndexField (opens new window)
- Description: ES field annotation, corresponding to MP's @TableField annotation,Before v0.9.40 this annotation was @TableField
- Where to use: The field in the entity class that is used as the ES index field
- Examples of usage scenarios:
- The fields in the entity class are not the actual fields in ES. For example, the entity class is used directly as a DTO, and some irrelevant fields that do not exist in ES are added. At this time, you can mark this field so that the EE framework can skip this. field, this field is not processed.
- The update strategy of the field, for example, when the update interface is called, the field of the entity class is not updated until it is not Null or a non-empty string. At this time, a field annotation can be added to mark the update strategy for the specified field.
- When you need to aggregate fields of type text or keyword_tex, you can specify its fieldData=true, otherwise es will report an error.
- Customize the name of the specified field. For example, the field is called wu-la in es, but it is called ula in the entity model. At this time, you can specify value="wu-la" in value.
- In the automatic managed index mode, the index tokenizer and index field type can be specified.
- In the automatic managed index mode, you can specify the format of the date in the index.
- You can specify to automatically add the configuration of ignoring case to the specified fields when creating indexes.
- ...
Example of use:
public class Document {
// Other fields are omitted here...
// Scenario 1: Mark fields that do not exist in es
@IndexField(exist = false)
private String notExistsField;
// Scenario 2: When updating, this field will only be updated if it is not an empty string
@IndexField(strategy = FieldStrategy.NOT_EMPTY)
private String creator;
// Scenario 3: specify fieldData
@IndexField(fieldType = FieldType.TEXT, fieldData = true)
private String filedData;
// Scenario 4: Custom field name
@IndexField("wu-la")
private String ula;
// Scenario 5: Support the format type of the date field in the es index
@IndexField(fieldType = FieldType.DATE, dateFormat = "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis")
private String gmtCreate;
// Scenario 6: Support the tokenizer type of the specified field in the es index
@IndexField(fieldType = FieldType.TEXT, analyzer = Analyzer.IK_SMART, searchAnalyzer = Analyzer.IK_MAX_WORD)
private String content;
// Scenario 7: support specified fields in es index ignore case, so that the term query is case-insensitive, only for keyword type fields in effect, es rules, not framework restrictions.
@IndexField(fieldType = FieldType.KEYWORD, ignoreCase = true)
private String caseTest;
// Scenario 8: Support dense vector type Dense vector type, dims must be specified at the same time, non-negative, the maximum is 2048
@IndexField(fieldType = FieldType.DENSE_VECTOR, dims = 3)
private double[] vector;
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
property | type | must specify | default value | description |
---|---|---|---|---|
value | String | No | "" | Field name |
exist | boolean | no | true | whether the field exists |
fieldType | Enum | No | FieldType.NONE | The type of the field in the es index |
fieldData | boolean | No | false | Whether the text type field supports aggregation |
analyzer | String | No | Analyzer.NONE | The tokenizer used when indexing documents |
searchAnalyzer | String | No | Analyzer.NONE | Query tokenizer |
strategy | Enum | No | FieldStrategy.DEFAULT | Field validation strategy |
dateFormat | String | No | "" | The date format in the es index, such as yyyy-MM-dd |
nestedClass | Class | No | DefaultNestedClass.class | Nested Class |
parentName | String | No | "" | Parent-child document-parent name |
childName | String | No | "" | Parent-child document-child name |
joinFieldClass | Class | No | JoinField.class | Parent-child document-parent-child type relationship field class |
ignoreCase | boolean | No | false | Whether keyword type fields ignore case |
ignoreAbove | int | no | 256 | The maximum length that the string will be indexed or stored |
scalingFactor | int | No | 100 | Used to specify the scaling factor of floating point fields. Scaled_float type fields must specify this parameter, otherwise ES will report an error when creating an index |
denseVector | String | No | "" | Dense vector type, can be used for vector retrieval |
dims | int | No | -1 | The dimension size of the vector, which cannot exceed 2048 and is non-negative |
Tips
- There are 3 types of update strategies:
- NOT_NULL: Non-Null judgment, when the field value is not Null, will be updated
- NOT_EMPTY: non-empty judgment, the field value will only be updated when the field value is not an empty string
- IGNORE: Ignore the judgment, no matter what the field value is, it will be updated
Scenario 4 and Scenario 5 only take effect in the automatic index hosting mode. If the manual index processing mode is enabled, the user needs to manually call the API provided by me to pass in the corresponding tokenizer and date formatting parameters to create/update the index .
# @MultiIndexField (opens new window)
-Description: Multi-field annotation -Use location: a single field in the entity class is expected to use multiple word splitters or fields with multiple field types. -Examples of usage scenarios: For example, a field wants to be queried by both Chinese word breakers and Pinyin word breakers.
Attribute | Type | You must specify | Default | Description |
---|---|---|---|---|
mainIndexField | @IndexField | Yes | -The main field must be specified. Please refer to @IndexField | above for usage. |
innerindexfield | @ innerindexfield [] | No | {} | Internal field can be an empty array. When the internal field is not specified, the annotation is downgraded to @IndexField, which is consistent with the annotation effect of @IndexField |
# @InnerIndexField (opens new window)
-Description: Internal field comments -Use location: @MultiIndexField inside -Examples of usage scenarios: For example, if you want to query a field with both Chinese word breakers and Pinyin word breakers, you can specify it in @MultiIndexField.
Attribute | Type | You must specify | Default | Description |
---|---|---|---|---|
suffix | String | is an internal field suffix of | - | |
fieldType | FieldType | is the field type of | internal field. This enumeration is the same as the FieldType in @IndexField, and the usage can be directly referred to | |
Analyzer | String | No | - | The index word breaker is the same as the analyzer in @IndexField, and the usage can be directly referred to |
searchAnalyzer | String | No | - | The query word breaker is the same as the Analyzer in @IndexField, and the usage can be directly referenced |
ignoreAbove | int | No | 256 | Internal field, the maximum length of the string to be indexed or stored |
Example of use.
public class Document {
/**
* composite field, this annotation and SpringData MultiField usage similar to the scenario for the same field through a variety of word splitter search
*/
@MultiIndexField(mainIndexField = @IndexField(fieldType = FieldType.KEYWORD),
otherIndexFields = {@InnerIndexField(suffix = "zh", fieldType = FieldType.TEXT, analyzer = Analyzer.IK_SMART),
@InnerIndexField(suffix = "pinyin", fieldType = FieldType.TEXT, analyzer = Analyzer.PINYIN)})
private String multiField;
}
2
3
4
5
6
7
8
9
Sample query.
@Test
public void testMultiFieldSelect() {
// The name of the drug is Calcium Gluconate in Chinese, putaotangsuangaikoufurongye in Chinese.
// Users can search by fuzzy search, e.g. if you type Calcium or Gluconate or putaotang, the corresponding drug will be searched.
LambdaEsQueryWrapper<Document> wrapper = new LambdaEsQueryWrapper<>(); wrapper.match("match", "match", "match", "match", "match", "match", "match", "match")
wrapper.match("english", "Calcium")
.or()
.match("multi_field.zh", "glucose")
.or()
.match("multi_field.pinyin", "putaotang");
List<Document> documents = documentMapper.selectList(wrapper);
System.out.println(documents);
}
2
3
4
5
6
7
8
9
10
11
12
13
In the above use case, the hump is turned on automatically to underscore, so the field name is "multi_field", in fact, in the query the user only needs to use the "field name.suffix" combination, you can determine which internal field is currently enabled, when querying the main field, there is no need to specify the suffix, the direct field name can be.
# @HighLight (opens new window)
-Description: Highlight the note -Usage location: the queried field that needs to be highlighted in the entity class. -Use scenarios as examples: for example, enter the keyword "old man" to query, and expect the part containing "old man" in the content to be displayed in red or bold.
Attribute | Type | You must specify | Default | Description |
---|---|---|---|---|
mappingField | String | No | "" | Highlight the name of the content mapping field. For example, if I want to assign the highlighted content" Old Man "to the field pushCar, I can specify this attribute value as pushCar |
fragmentSize | int | No | 100 | Intercept length of highlighted field, the default is 100 |
numberOfFragments | int | No | -1 | The number of highlighted fragments returned by search, and all are returned by default |
preTag | String | No | < em > | Highlight the tag, and the highlighted content will be behind preTag |
postTag | String | No | < /em > | Highlight the tag, and the highlighted content will come before the postTag |
highlighttype | highlighttypeenum | No | UNIFIED | Highlight type |
requireFieldMatch | boolean | no | true | Whether the highlighted content needs to match the query field. The default value is true. When it is no, non-query fields in the hit content will also be highlighted if they contain highlighted content |
# @Score (opens new window)
- Description: Score annotation
- Where to use: Fields in entity classes that are returned as ES query scores
- Example of usage scenarios: For example, when you need to know the score of this matching query, you can add a field of type Float/float to the entity class, and add the @Score annotation to the field. In subsequent queries, if es has Return the score of the current query, then this score will be automatically mapped to this field
property | type | must specify | default value | description |
---|---|---|---|---|
decimalPlaces | int | No | 0 | The score retains decimal places, it is not processed by default, keep the score value returned by es |
# @Distance (opens new window)
- Description: Distance annotation
- Use location: The returned field in the entity class is used as the ES geographic location sort distance value
- Example of usage scenarios: For example, if you need to know the data queried by distance from near to far, how far is the actual distance from a certain coordinate, you can add a field of type Double/double to the entity class, and add @ to this field Distance annotation, in subsequent queries, if es has a return distance, this distance will be automatically mapped to this field
property | type | must specify | default value | description |
---|---|---|---|---|
decimalPlaces | int | No | 0 | The distance retains decimal places, it is not processed by default, and the distance value returned by es is maintained |
sortBuilderIndex | int | No | 0 | The position of the sort field in sortBuilders, the default is 0, if there are multiple sorters, specify its position |
# @EsDS (opens new window)
- Description: Multiple data source annotations
- Usage location: Custom Mapper inherited from BaseEsMapper
- Examples of usage scenarios: For example, if there are multiple ESs and you want different Mappers to connect to different ESs, the usage is the same as @DS in Mybatis-Plus.
- For more usage introduction, please go to the Core Function -> Dynamic Data Source Support chapter to learn.
Property | Type | Required | Default value | Description |
---|---|---|---|---|
value | String | No | "" | Data source name, consistent with the one specified in the configuration file |
# @Join (opens new window)
Description: Join parent-child type annotation, used to express parent-child type index relationship
Location of use: Parent-child type root node Root class
/**
* The Document root document has sub-documents Author (author) and Comment (comments), and Author also has a sub-document Contact (contact information)
*Join parent-child type structure is as follows
*Document
* / \
* Comment Author
*\
*Contact
* The above structure can be expressed by @Join annotation and @Node annotation. Please refer to the following case
**/
@Join(nodes = {@Node(parentClass = Document.class, childClasses = {Author.class, Comment.class}), @Node(parentClass = Author.class, childClasses = Contact.class)})
public class Document {
// Omit other irrelevant fields
}
2
3
4
5
6
7
8
9
10
11
12
13
14
| Property | Type | Required | Default value | Description | |---|--------------|------|---|------------------ -----------------------| |joinField| String | No |""| The name of the join field in the index. The default is joinField (recommended) | |rootAlias| String | No |""| Root node alias If not specified, the lowercase name of the root class with the current annotation will be used as the root node alias by default (recommended) | |nodes| Annotation[] | Yes |""| List of non-root nodes | |eagerGlobalOrdinals| boolean | No | true | Whether to create global ordinals, created by default, which can improve query performance |
Warm reminder
For more information on the use of this annotation, please refer to the Join parent-child type chapter document.
# @Node (opens new window)
Description: Join parent-child type annotation, used to express parent-child type index relationship
Location of use: Parent-child type root node Root class
/**
* The Document root document has sub-documents Author (author) and Comment (comments), and Author also has a sub-document Contact (contact information)
*Join parent-child type structure is as follows
*Document
* / \
* Comment Author
*\
*Contact
* The above structure can be expressed by @Join annotation and @Node annotation. Please refer to the following case
**/
@Join(nodes = {@Node(parentClass = Document.class, childClasses = {Author.class, Comment.class}), @Node(parentClass = Author.class, childClasses = Contact.class)})
public class Document {
// Omit other irrelevant fields
}
2
3
4
5
6
7
8
9
10
11
12
13
14
| Properties | Type | Required | Default | Description | |---|--------|------|-----|----------------------- ------------------| |parentAlias| String | No | "" | Parent document alias is optional. If not specified, the default value is parentClass class name in lowercase (recommended) | |parentClass| Class | Yes | - | Parent document entity class, required | |childAliases| String | No | "" | A list of subdocument aliases. If not specified, it will be a lowercase list of subdocument class names (recommended). If you want to customize it, it must be consistent with the number and order of childClasses | |childClasses| Class | Yes | - | Subdocument entity class list, required |
Warm reminder
For more information on the use of this annotation, please refer to the Join parent-child type chapter document.
# other notes
In addition to the above high-frequency annotations, some other annotations are occasionally used in the project, such as the highlight annotation @HighLight, such as the interceptor annotation @Intercepts and other annotations, which we will introduce in detail in the specific chapters below, only listed here. A few annotations must be mastered, and other annotations can be learned as needed.