DATAES-2 Applied spring-data formatting to all sources

This commit is contained in:
akonczak 2013-05-12 19:37:25 +01:00
parent 5e917b5ff6
commit 7df712a3b6
107 changed files with 7804 additions and 6535 deletions

View File

@ -0,0 +1,820 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<profiles version="12">
<profile kind="CodeFormatterProfile" name="Spring Data"
version="12">
<setting
id="org.eclipse.jdt.core.formatter.comment.insert_new_line_before_root_tags"
value="insert" />
<setting id="org.eclipse.jdt.core.formatter.disabling_tag"
value="@formatter:off" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_annotation"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_parameters"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_type_declaration"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_arguments"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.brace_position_for_anonymous_type_declaration"
value="end_of_line" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_case"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_brace_in_array_initializer"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.comment.new_lines_at_block_boundaries"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_annotation_declaration"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_before_closing_brace_in_array_initializer"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_annotation"
value="do not insert" />
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_field"
value="0" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_while"
value="do not insert" />
<setting id="org.eclipse.jdt.core.formatter.use_on_off_tags"
value="false" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_annotation_type_member_declaration"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_before_else_in_if_statement"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_prefix_operator"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.keep_else_statement_on_same_line"
value="false" />
<setting id="org.eclipse.jdt.core.formatter.insert_space_after_ellipsis"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.comment.insert_new_line_for_parameter"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_annotation_type_declaration"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.indent_breaks_compare_to_cases"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_multiple_fields"
value="16" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_expressions_in_array_initializer"
value="16" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_conditional_expression"
value="80" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_for"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_binary_operator"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_wildcard"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.brace_position_for_array_initializer"
value="end_of_line" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_enum_constant"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_before_finally_in_try_statement"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_local_variable"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_before_catch_in_try_statement"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_while"
value="insert" />
<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_package"
value="1" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_type_parameters"
value="insert" />
<setting id="org.eclipse.jdt.core.formatter.continuation_indentation"
value="2" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_postfix_operator"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_method_invocation"
value="16" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_arguments"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_superinterfaces"
value="do not insert" />
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_new_chunk"
value="1" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_binary_operator"
value="insert" />
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_package"
value="0" />
<setting id="org.eclipse.jdt.core.compiler.source" value="1.7" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_constant_arguments"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_constructor_declaration"
value="do not insert" />
<setting id="org.eclipse.jdt.core.formatter.comment.format_line_comments"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_arguments"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_enum_declarations"
value="insert" />
<setting id="org.eclipse.jdt.core.formatter.join_wrapped_lines"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_block"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_explicit_constructor_call"
value="16" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_invocation_arguments"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.blank_lines_before_member_type"
value="1" />
<setting
id="org.eclipse.jdt.core.formatter.align_type_members_on_columns"
value="false" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_enum_constant"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_for"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_method_declaration"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_selector_in_method_invocation"
value="16" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_switch"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_unary_operator"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_case"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.comment.indent_parameter_description"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_declaration"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_switch"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_declaration"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_parameters"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_block_comment"
value="false" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_type_declaration"
value="insert" />
<setting id="org.eclipse.jdt.core.formatter.lineSplit" value="120" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_if"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_between_brackets_in_array_type_reference"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_parenthesized_expression"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_explicitconstructorcall_arguments"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_constructor_declaration"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.blank_lines_before_first_class_body_declaration"
value="0" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_method"
value="insert" />
<setting id="org.eclipse.jdt.core.formatter.indentation.size"
value="2" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_declaration"
value="do not insert" />
<setting id="org.eclipse.jdt.core.formatter.enabling_tag"
value="@formatter:on" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_enum_constant"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_superclass_in_type_declaration"
value="16" />
<setting id="org.eclipse.jdt.core.formatter.alignment_for_assignment"
value="0" />
<setting id="org.eclipse.jdt.core.compiler.problem.assertIdentifier"
value="error" />
<setting id="org.eclipse.jdt.core.formatter.tabulation.char"
value="tab" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_parameters"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_try_resources"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_prefix_operator"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_body"
value="true" />
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_method"
value="1" />
<setting
id="org.eclipse.jdt.core.formatter.wrap_outer_expressions_when_nested"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.format_guardian_clause_on_one_line"
value="false" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_for"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_cast"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_constructor_declaration"
value="16" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_labeled_statement"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.brace_position_for_annotation_type_declaration"
value="end_of_line" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_method_body"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_method_declaration"
value="0" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_method_invocation"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_try"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_allocation_expression"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_enum_constant"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_annotation"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_at_in_annotation_type_declaration"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_throws"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_if"
value="do not insert" />
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_switch"
value="end_of_line" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_throws"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_return"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_conditional"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_question_in_wildcard"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_try"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_allocation_expression"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.comment.preserve_white_space_between_code_and_line_comments"
value="false" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_parenthesized_expression_in_throw"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_type_arguments"
value="do not insert" />
<setting id="org.eclipse.jdt.core.compiler.problem.enumIdentifier"
value="error" />
<setting
id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_switch"
value="false" />
<setting id="org.eclipse.jdt.core.formatter.insert_space_before_ellipsis"
value="do not insert" />
<setting id="org.eclipse.jdt.core.formatter.brace_position_for_block"
value="end_of_line" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_inits"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.brace_position_for_method_declaration"
value="end_of_line" />
<setting id="org.eclipse.jdt.core.formatter.compact_else_if"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.wrap_before_or_operator_multicatch"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_array_initializer"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_increments"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.format_line_comment_starting_on_first_column"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_bracket_in_array_reference"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_field"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.brace_position_for_enum_constant"
value="end_of_line" />
<setting id="org.eclipse.jdt.core.formatter.comment.indent_root_tags"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_declarations"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_union_type_in_multicatch"
value="16" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_explicitconstructorcall_arguments"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_switch"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_method_declaration_parameters"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_superinterfaces"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_allocation_expression"
value="do not insert" />
<setting id="org.eclipse.jdt.core.formatter.tabulation.size"
value="2" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_type_reference"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_after_opening_brace_in_array_initializer"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_closing_brace_in_block"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_reference"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_constant"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_arguments"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_constructor_declaration"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_throws"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_if"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.comment.clear_blank_lines_in_javadoc_comment"
value="false" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_constructor_declaration"
value="16" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_assignment_operator"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_assignment_operator"
value="insert" />
<setting id="org.eclipse.jdt.core.formatter.indent_empty_lines"
value="false" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_synchronized"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_closing_paren_in_cast"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_declaration_parameters"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.brace_position_for_block_in_case"
value="end_of_line" />
<setting
id="org.eclipse.jdt.core.formatter.number_of_empty_lines_to_preserve"
value="1" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_declaration"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_catch"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_constructor_declaration"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_method_invocation"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_bracket_in_array_reference"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_qualified_allocation_expression"
value="16" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_and_in_type_parameter"
value="insert" />
<setting id="org.eclipse.jdt.core.compiler.compliance" value="1.7" />
<setting
id="org.eclipse.jdt.core.formatter.continuation_indentation_for_array_initializer"
value="2" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_between_empty_brackets_in_array_allocation_expression"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_at_in_annotation_type_declaration"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_allocation_expression"
value="16" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_cast"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_unary_operator"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_parameterized_type_reference"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_anonymous_type_declaration"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.keep_empty_array_initializer_on_one_line"
value="false" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_enum_declaration"
value="insert" />
<setting id="org.eclipse.jdt.core.formatter.keep_imple_if_on_one_line"
value="false" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_constructor_declaration_parameters"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_closing_angle_bracket_in_type_parameters"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_at_end_of_file_if_missing"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_for"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_labeled_statement"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_parameterized_type_reference"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_type_declaration"
value="16" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_binary_expression"
value="16" />
<setting
id="org.eclipse.jdt.core.formatter.brace_position_for_enum_declaration"
value="end_of_line" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_type"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_while"
value="do not insert" />
<setting id="org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode"
value="enabled" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_try"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.put_empty_statement_on_new_line"
value="true" />
<setting id="org.eclipse.jdt.core.formatter.insert_new_line_after_label"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_parameter"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_type_parameters"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_method_invocation"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_before_while_in_do_statement"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_enum_constant"
value="16" />
<setting
id="org.eclipse.jdt.core.formatter.comment.format_javadoc_comments"
value="true" />
<setting id="org.eclipse.jdt.core.formatter.comment.line_length"
value="120" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_after_annotation_on_package"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.blank_lines_between_import_groups"
value="1" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_enum_constant_arguments"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.brace_position_for_constructor_declaration"
value="end_of_line" />
<setting
id="org.eclipse.jdt.core.formatter.number_of_blank_lines_at_beginning_of_method_body"
value="0" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_conditional"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_type_header"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_annotation_type_member_declaration"
value="do not insert" />
<setting id="org.eclipse.jdt.core.formatter.wrap_before_binary_operator"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_declaration_header"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.blank_lines_between_type_declarations"
value="1" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_synchronized"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.indent_statements_compare_to_block"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_superinterfaces_in_enum_declaration"
value="16" />
<setting id="org.eclipse.jdt.core.formatter.join_lines_in_comments"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_question_in_conditional"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_field_declarations"
value="do not insert" />
<setting id="org.eclipse.jdt.core.formatter.alignment_for_compact_if"
value="16" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_for_inits"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.indent_switchstatements_compare_to_cases"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_array_initializer"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_default"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_and_in_type_parameter"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_between_empty_parens_in_constructor_declaration"
value="do not insert" />
<setting id="org.eclipse.jdt.core.formatter.blank_lines_before_imports"
value="1" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_assert"
value="insert" />
<setting id="org.eclipse.jdt.core.formatter.comment.format_html"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_throws_clause_in_method_declaration"
value="16" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_angle_bracket_in_type_parameters"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_bracket_in_array_allocation_expression"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_anonymous_type_declaration"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_colon_in_conditional"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_angle_bracket_in_parameterized_type_reference"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_for"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_postfix_operator"
value="do not insert" />
<setting id="org.eclipse.jdt.core.formatter.comment.format_source_code"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_synchronized"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_allocation_expression"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_constructor_declaration_throws"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_parameters_in_method_declaration"
value="16" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_brace_in_array_initializer"
value="insert" />
<setting id="org.eclipse.jdt.core.compiler.codegen.targetPlatform"
value="1.7" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_resources_in_try"
value="80" />
<setting
id="org.eclipse.jdt.core.formatter.use_tabs_only_for_leading_indentations"
value="false" />
<setting
id="org.eclipse.jdt.core.formatter.alignment_for_arguments_in_annotation"
value="0" />
<setting id="org.eclipse.jdt.core.formatter.comment.format_header"
value="false" />
<setting
id="org.eclipse.jdt.core.formatter.comment.format_block_comments"
value="false" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_enum_constant"
value="do not insert" />
<setting id="org.eclipse.jdt.core.formatter.alignment_for_enum_constants"
value="0" />
<setting
id="org.eclipse.jdt.core.formatter.insert_new_line_in_empty_block"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_annotation_declaration_header"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_parenthesized_expression"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_parenthesized_expression"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_catch"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_multiple_local_declarations"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_switch"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_comma_in_for_increments"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_invocation"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_colon_in_assert"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.brace_position_for_type_declaration"
value="end_of_line" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_brace_in_array_initializer"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_between_empty_braces_in_array_initializer"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_opening_paren_in_method_declaration"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_for"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_paren_in_catch"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_parameterized_type_reference"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_field_declarations"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_closing_paren_in_annotation"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_parameterized_type_reference"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_method_invocation_arguments"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.comment.new_lines_at_javadoc_boundaries"
value="true" />
<setting id="org.eclipse.jdt.core.formatter.blank_lines_after_imports"
value="1" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_comma_in_multiple_local_declarations"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.indent_body_declarations_compare_to_enum_constant_header"
value="true" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_after_semicolon_in_for"
value="insert" />
<setting
id="org.eclipse.jdt.core.formatter.never_indent_line_comments_on_first_column"
value="false" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_semicolon_in_try_resources"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.insert_space_before_opening_angle_bracket_in_type_arguments"
value="do not insert" />
<setting
id="org.eclipse.jdt.core.formatter.never_indent_block_comments_on_first_column"
value="false" />
<setting
id="org.eclipse.jdt.core.formatter.keep_then_statement_on_same_line"
value="false" />
</profile>
</profiles>

248
pom.xml
View File

@ -1,131 +1,132 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>1.0.0.BUILD-SNAPSHOT</version>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-elasticsearch</artifactId>
<version>1.0.0.BUILD-SNAPSHOT</version>
<parent>
<parent>
<groupId>org.springframework.data.build</groupId>
<artifactId>spring-data-parent</artifactId>
<version>1.1.0.BUILD-SNAPSHOT</version>
<relativePath>../spring-data-build/parent/pom.xml</relativePath>
</parent>
<name>Spring Data Elasticsearch</name>
<description>Spring Data Implementation for Elasticsearch</description>
<url>https://github.com/SpringSource/spring-data-elasticsearch</url>
<name>Spring Data Elasticsearch</name>
<description>Spring Data Implementation for Elasticsearch</description>
<url>https://github.com/SpringSource/spring-data-elasticsearch</url>
<properties>
<properties>
<dist.key>DATAES</dist.key>
<dist.key>DATAES</dist.key>
<commonscollections>3.2.1</commonscollections>
<commonslang>2.6</commonslang>
<elasticsearch>0.90.0</elasticsearch>
<jackson>1.9.2</jackson>
<springdata.commons>1.6.0.BUILD-SNAPSHOT</springdata.commons>
<commonscollections>3.2.1</commonscollections>
<commonslang>2.6</commonslang>
<elasticsearch>0.90.0</elasticsearch>
<jackson>1.9.2</jackson>
<springdata.commons>1.6.0.BUILD-SNAPSHOT</springdata.commons>
</properties>
</properties>
<dependencies>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring}</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring}</version>
</dependency>
<!-- For JavaConfig -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
<scope>test</scope>
</dependency>
<!-- For JavaConfig -->
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.2.2</version>
<scope>test</scope>
</dependency>
<!-- SPRING DATA -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>${springdata.commons}</version>
</dependency>
<!-- SPRING DATA -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-commons</artifactId>
<version>${springdata.commons}</version>
</dependency>
<!-- APACHE -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commonslang}</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>${commonscollections}</version>
</dependency>
<!-- APACHE -->
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commonslang}</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>${commonscollections}</version>
</dependency>
<!-- JODA Time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime}</version>
</dependency>
<!-- JODA Time -->
<dependency>
<groupId>joda-time</groupId>
<artifactId>joda-time</artifactId>
<version>${jodatime}</version>
</dependency>
<!-- Elasticsearch -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elasticsearch}</version>
</dependency>
<!-- Elasticsearch -->
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>elasticsearch</artifactId>
<version>${elasticsearch}</version>
</dependency>
<!-- Jackson JSON Mapper -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${jackson}</version>
</dependency>
<!-- Jackson JSON Mapper -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>${jackson}</version>
</dependency>
<!-- CDI -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>${cdi}</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<!-- CDI -->
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>${cdi}</version>
<scope>provided</scope>
<optional>true</optional>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.openwebbeans.test</groupId>
<artifactId>cditest-owb</artifactId>
<version>${webbeans}</version>
<scope>test</scope>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.openwebbeans.test</groupId>
<artifactId>cditest-owb</artifactId>
<version>${webbeans}</version>
<scope>test</scope>
</dependency>
</dependencies>
</dependencies>
<build>
<plugins>
<plugin>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-assembly-plugin</artifactId>
</plugin>
@ -133,18 +134,18 @@
<groupId>org.codehaus.mojo</groupId>
<artifactId>wagon-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</plugins>
</build>
<developers>
<developer>
<id>biomedcentral</id>
<name>BioMed Central Development Team</name>
<timezone>+0</timezone>
</developer>
</developers>
<developers>
<developer>
<id>biomedcentral</id>
<name>BioMed Central Development Team</name>
<timezone>+0</timezone>
</developer>
</developers>
<repositories>
<repositories>
<repository>
<id>spring-libs-snapshot</id>
<url>http://repo.springsource.org/lib-snapshot-local</url>
@ -152,19 +153,20 @@
</repositories>
<scm>
<url>https://github.com/SpringSource/spring-data-elasticsearch</url>
<connection>scm:git:git://github.com/SpringSource/spring-data-elasticsearch.git</connection>
<developerConnection>scm:git:ssh://git@github.com:SpringSource/spring-data-elasticsearch.git</developerConnection>
</scm>
<url>https://github.com/SpringSource/spring-data-elasticsearch</url>
<connection>scm:git:git://github.com/SpringSource/spring-data-elasticsearch.git</connection>
<developerConnection>scm:git:ssh://git@github.com:SpringSource/spring-data-elasticsearch.git
</developerConnection>
</scm>
<ciManagement>
<system>Bamboo</system>
<url>http://build.springsource.org/browse/SPRINGDATAESh</url>
</ciManagement>
<ciManagement>
<system>Bamboo</system>
<url>http://build.springsource.org/browse/SPRINGDATAES</url>
</ciManagement>
<issueManagement>
<system>JIRA</system>
<url>https://jira.springsource.org/browse/DATAES</url>
<issueManagement>
<system>JIRA</system>
<url>https://jira.springsource.org/browse/DATAES</url>
</issueManagement>
</project>

View File

@ -5,11 +5,11 @@
<bookinfo>
<title>Spring Data Elasticsearch</title>
<authorgroup>
<author>
<firstname>BioMed Central</firstname>
<surname>Development Team</surname>
</author>
</authorgroup>
<author>
<firstname>BioMed Central</firstname>
<surname>Development Team</surname>
</author>
</authorgroup>
<legalnotice>
<para>
Copies of this document may be made for your own use and for
@ -35,8 +35,10 @@
<part id="reference">
<title>Reference Documentation</title>
<xi:include href="https://raw.github.com/SpringSource/spring-data-commons/1.4.0.RC1/src/docbkx/repositories.xml">
<xi:fallback href="../../../spring-data-commons/src/docbkx/repositories.xml" />
<xi:include
href="https://raw.github.com/SpringSource/spring-data-commons/1.4.0.RC1/src/docbkx/repositories.xml">
<xi:fallback
href="../../../spring-data-commons/src/docbkx/repositories.xml" />
</xi:include>
<xi:include href="reference/data-elasticsearch.xml" />

View File

@ -3,13 +3,16 @@
"http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd">
<preface id="preface">
<title>Preface</title>
<para>The Spring Data Elasticsearch project applies core Spring concepts to
<para>The Spring Data Elasticsearch project applies core Spring
concepts to
the
development of solutions using the Elasticsearch Search Engine.
development of solutions using the Elasticsearch Search
Engine.
We have povided a "template" as a high-level abstraction for
storing,querying,sorting and faceting documents. You will notice similarities
to the Spring data solr and
mongodb support in the Spring Framework.
storing,querying,sorting and faceting documents. You will notice
similarities
to the Spring data solr and
mongodb support in the Spring Framework.
</para>
<section id="project">
<title>Project Metadata</title>
@ -17,7 +20,8 @@
<listitem>
<para>
Version Control -
<ulink url="git://github.com/BioMedCentralLtd/spring-data-elasticsearch.git">git://github.com/BioMedCentralLtd/spring-data-elasticsearch.git
<ulink
url="git://github.com/BioMedCentralLtd/spring-data-elasticsearch.git">git://github.com/BioMedCentralLtd/spring-data-elasticsearch.git
</ulink>
</para>
</listitem>
@ -28,7 +32,8 @@
<para>
Requires
<ulink url="http://www.elasticsearch.org/download/">Elasticsearch</ulink>
0.20.2 and above or optional dependency or not even that if you are using Embedded Node Client
</para>
0.20.2 and above or optional dependency or not even that if you are
using Embedded Node Client
</para>
</section>
</preface>

View File

@ -15,8 +15,10 @@
<title>Spring Namespace</title>
<para>
The Spring Data Elasticsearch module contains a custom namespace allowing
definition of repository beans as well as elements for instantiating
The Spring Data Elasticsearch module contains a custom namespace
allowing
definition of repository beans as well as elements for
instantiating
a
<classname>ElasticsearchServer</classname>
.
@ -32,7 +34,7 @@
<example>
<title>Setting up Elasticsearch repositories using Namespace</title>
<programlisting language="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
<programlisting language="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
@ -56,7 +58,7 @@ http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.
<example>
<title>Transport Client using Namespace</title>
<programlisting language="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
<programlisting language="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
@ -71,7 +73,7 @@ http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.
<example>
<title>Node Client using Namespace</title>
<programlisting language="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
<programlisting language="xml">&lt;?xml version="1.0" encoding="UTF-8"?&gt;
&lt;beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
@ -87,13 +89,15 @@ http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.
</section>
<section id="elasticsearch.annotation">
<title>Annotation based configuration</title>
<para>The Spring Data Elasticsearch repositories support cannot only be
<para>The Spring Data Elasticsearch repositories support cannot only
be
activated through an XML namespace but also using an annotation
through JavaConfig.
</para>
<example>
<title>Spring Data Elasticsearch repositories using JavaConfig</title>
<programlisting language="java">
<title>Spring Data Elasticsearch repositories using JavaConfig
</title>
<programlisting language="java">
@Configuration
@EnableElasticsearchRepositories(basePackages = "org/springframework/data/elasticsearch/repositories")
static class Config {
@ -122,12 +126,14 @@ return new ElasticsearchTemplate(nodeBuilder().local(true).node().client());
</section>
<section id="elasticsearch.cdi">
<title>Elasticsearch Repositores using CDI</title>
<para>The Spring Data Elasticsearch repositories can also be set up using CDI
<para>The Spring Data Elasticsearch repositories can also be set up
using CDI
functionality.
</para>
<example>
<title>Spring Data Elasticsearch repositories using JavaConfig</title>
<programlisting language="java">class ElasticsearchTemplateProducer {
<title>Spring Data Elasticsearch repositories using JavaConfig
</title>
<programlisting language="java">class ElasticsearchTemplateProducer {
@Produces
@ApplicationScoped
@ -157,9 +163,11 @@ public void setRepository(ProductRepository repository) {
<section id="elasticsearch.query-methods.finders">
<title>Query lookup strategies</title>
<para>
The Elasticsearch module supports all basic query building feature as String,Abstract,Criteria or
The Elasticsearch module supports all basic query building
feature as String,Abstract,Criteria or
have
it being derived from the method name.
it being derived from the
method name.
</para>
<simplesect>
@ -180,11 +188,13 @@ public void setRepository(ProductRepository repository) {
<title>Query creation</title>
<para>
Generally the query creation mechanism for Elasticsearch works as described
Generally the query creation mechanism for Elasticsearch works as
described
in
<xref linkend="repositories.query-methods" />
. Here's a short example
of what a Elasticsearch query method translates into:
of what a Elasticsearch query method
translates into:
<example>
<title>Query creation from method names</title>
<programlisting language="java">public interface BookRepository extends Repository&lt;Book, String&gt; {
@ -192,7 +202,7 @@ public void setRepository(ProductRepository repository) {
}</programlisting>
<para>
The method name above will be translated into the following
Elasticsearch json query
Elasticsearch json query
</para>
<programlisting>
{ "bool" :
@ -227,7 +237,8 @@ public void setRepository(ProductRepository repository) {
<code>findByNameAndPrice</code>
</entry>
<entry>
<code>{"bool" : {"must" : [ {"field" : {"name" : "?"}}, {"field" : {"price" : "?"}} ]}}</code>
<code>{"bool" : {"must" : [ {"field" : {"name" : "?"}},
{"field" : {"price" : "?"}} ]}}</code>
</entry>
</row>
<row>
@ -238,7 +249,8 @@ public void setRepository(ProductRepository repository) {
<code>findByNameOrPrice</code>
</entry>
<entry>
<code>{"bool" : {"should" : [ {"field" : {"name" : "?"}}, {"field" : {"price" : "?"}} ]}}</code>
<code>{"bool" : {"should" : [ {"field" : {"name" : "?"}},
{"field" : {"price" : "?"}} ]}}</code>
</entry>
</row>
<row>
@ -260,7 +272,8 @@ public void setRepository(ProductRepository repository) {
<code>findByNameNot</code>
</entry>
<entry>
<code>{"bool" : {"must_not" : {"field" : {"name" : "?"}}}}</code>
<code>{"bool" : {"must_not" : {"field" : {"name" : "?"}}}}
</code>
</entry>
</row>
<row>
@ -271,7 +284,9 @@ public void setRepository(ProductRepository repository) {
<code>findByPriceBetween</code>
</entry>
<entry>
<code>{"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : ?,"include_lower" : true,"include_upper" : true}}}}}</code>
<code>{"bool" : {"must" : {"range" : {"price" : {"from" :
?,"to" : ?,"include_lower" : true,"include_upper" : true}}}}}
</code>
</entry>
</row>
<row>
@ -282,7 +297,9 @@ public void setRepository(ProductRepository repository) {
<code>findByPriceLessThan</code>
</entry>
<entry>
<code>{"bool" : {"must" : {"range" : {"price" : {"from" : null,"to" : ?,"include_lower" : true,"include_upper" : true}}}}}</code>
<code>{"bool" : {"must" : {"range" : {"price" : {"from" :
null,"to" : ?,"include_lower" : true,"include_upper" :
true}}}}}</code>
</entry>
</row>
<row>
@ -293,7 +310,9 @@ public void setRepository(ProductRepository repository) {
<code>findByPriceGreaterThan</code>
</entry>
<entry>
<code>{"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : null,"include_lower" : true,"include_upper" : true}}}}}</code>
<code>{"bool" : {"must" : {"range" : {"price" : {"from" :
?,"to" : null,"include_lower" : true,"include_upper" :
true}}}}}</code>
</entry>
</row>
<row>
@ -304,7 +323,9 @@ public void setRepository(ProductRepository repository) {
<code>findByPriceBefore</code>
</entry>
<entry>
<code>{"bool" : {"must" : {"range" : {"price" : {"from" : null,"to" : ?,"include_lower" : true,"include_upper" : true}}}}}</code>
<code>{"bool" : {"must" : {"range" : {"price" : {"from" :
null,"to" : ?,"include_lower" : true,"include_upper" :
true}}}}}</code>
</entry>
</row>
<row>
@ -315,7 +336,9 @@ public void setRepository(ProductRepository repository) {
<code>findByPriceAfter</code>
</entry>
<entry>
<code>{"bool" : {"must" : {"range" : {"price" : {"from" : ?,"to" : null,"include_lower" : true,"include_upper" : true}}}}}</code>
<code>{"bool" : {"must" : {"range" : {"price" : {"from" :
?,"to" : null,"include_lower" : true,"include_upper" :
true}}}}}</code>
</entry>
</row>
<row>
@ -326,7 +349,8 @@ public void setRepository(ProductRepository repository) {
<code>findByNameLike</code>
</entry>
<entry>
<code>{"bool" : {"must" : {"field" : {"name" : {"query" : "?*","analyze_wildcard" : true}}}}}</code>
<code>{"bool" : {"must" : {"field" : {"name" : {"query" :
"?*","analyze_wildcard" : true}}}}}</code>
</entry>
</row>
<row>
@ -337,7 +361,8 @@ public void setRepository(ProductRepository repository) {
<code>findByNameStartingWith</code>
</entry>
<entry>
<code>{"bool" : {"must" : {"field" : {"name" : {"query" : "?*","analyze_wildcard" : true}}}}}</code>
<code>{"bool" : {"must" : {"field" : {"name" : {"query" :
"?*","analyze_wildcard" : true}}}}}</code>
</entry>
</row>
<row>
@ -348,7 +373,8 @@ public void setRepository(ProductRepository repository) {
<code>findByNameEndingWith</code>
</entry>
<entry>
<code>{"bool" : {"must" : {"field" : {"name" : {"query" : "*?","analyze_wildcard" : true}}}}}</code>
<code>{"bool" : {"must" : {"field" : {"name" : {"query" :
"*?","analyze_wildcard" : true}}}}}</code>
</entry>
</row>
<row>
@ -359,7 +385,8 @@ public void setRepository(ProductRepository repository) {
<code>findByNameContaining</code>
</entry>
<entry>
<code>{"bool" : {"must" : {"field" : {"name" : {"query" : "*?*","analyze_wildcard" : true}}}}}</code>
<code>{"bool" : {"must" : {"field" : {"name" : {"query" :
"*?*","analyze_wildcard" : true}}}}}</code>
</entry>
</row>
<row>
@ -370,7 +397,8 @@ public void setRepository(ProductRepository repository) {
<code>findByNameIn(Collection&lt;String&gt;names)</code>
</entry>
<entry>
<code>{"bool" : {"must" : {"bool" : {"should" : [ {"field" : {"name" : "?"}}, {"field" : {"name" : "?"}} ]}}}}</code>
<code>{"bool" : {"must" : {"bool" : {"should" : [ {"field" :
{"name" : "?"}}, {"field" : {"name" : "?"}} ]}}}}</code>
</entry>
</row>
<row>
@ -381,7 +409,8 @@ public void setRepository(ProductRepository repository) {
<code>findByNameNotIn(Collection&lt;String&gt;names)</code>
</entry>
<entry>
<code>{"bool" : {"must_not" : {"bool" : {"should" : {"field" : {"name" : "?"}}}}}}</code>
<code>{"bool" : {"must_not" : {"bool" : {"should" : {"field" :
{"name" : "?"}}}}}}</code>
</entry>
</row>
<row>
@ -403,7 +432,8 @@ public void setRepository(ProductRepository repository) {
<code>findByAvailableTrue</code>
</entry>
<entry>
<code>{"bool" : {"must" : {"field" : {"available" : true}}}}</code>
<code>{"bool" : {"must" : {"field" : {"available" : true}}}}
</code>
</entry>
</row>
<row>
@ -414,7 +444,8 @@ public void setRepository(ProductRepository repository) {
<code>findByAvailableFalse</code>
</entry>
<entry>
<code>{"bool" : {"must" : {"field" : {"available" : false}}}}</code>
<code>{"bool" : {"must" : {"field" : {"available" : false}}}}
</code>
</entry>
</row>
<row>
@ -425,7 +456,8 @@ public void setRepository(ProductRepository repository) {
<code>findByAvailableTrueOrderByNameDesc</code>
</entry>
<entry>
<code>{"sort" : [{ "name" : {"order" : "desc"} }],"bool" : {"must" : {"field" : {"available" : true}}}}</code>
<code>{"sort" : [{ "name" : {"order" : "desc"} }],"bool" :
{"must" : {"field" : {"available" : true}}}}</code>
</entry>
</row>
</tbody>

View File

@ -6,9 +6,10 @@
<abstract>
<para>
This chapter covers additional support for Elasticsearch operations
that cannot be directly accessed via the repository
that cannot be directly accessed via the repository
interface.
It is recommended to add those operations as custom
It is
recommended to add those operations as custom
implementation as
described in
<xref linkend="repositories.custom-implementations" />
@ -21,7 +22,7 @@
Filter Builder improves query speed.
</para>
<example>
<programlisting language="java">
<programlisting language="java">
private ElasticsearchTemplate elasticsearchTemplate;
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchAllQuery())
@ -31,18 +32,19 @@ Page&lt;SampleEntity&gt; sampleEntities = elasticsearchTemplate.queryForPage(sea
</programlisting>
</example>
</section>
<section id="elasticsearch.scan.and.scroll">
<title>Using Scan And Scroll For Big Result Set</title>
<para>
Elasticsearch has scan and scroll feature for getting big result set in chunks.
<interfacename>ElasticsearchTemplate</interfacename>
has scan and scroll methods that can be used as below.
</para>
<example>
<title>
Using Scan and Scroll
</title>
<programlisting language="java">
<section id="elasticsearch.scan.and.scroll">
<title>Using Scan And Scroll For Big Result Set</title>
<para>
Elasticsearch has scan and scroll feature for getting big result set
in chunks.
<interfacename>ElasticsearchTemplate</interfacename>
has scan and scroll methods that can be used as below.
</para>
<example>
<title>
Using Scan and Scroll
</title>
<programlisting language="java">
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchAllQuery())
.withIndices("test-index")
@ -78,6 +80,6 @@ for(SearchHit searchHit : response.getHits()){
}
}
}</programlisting>
</example>
</section>
</example>
</section>
</chapter>

File diff suppressed because it is too large Load Diff

View File

@ -3,34 +3,33 @@
code highlight CSS resemblign the Eclipse IDE default color schema
@author Costin Leau
*/
.hl-keyword {
color: #7F0055;
font-weight: bold;
color: #7F0055;
font-weight: bold;
}
.hl-comment {
color: #3F5F5F;
font-style: italic;
color: #3F5F5F;
font-style: italic;
}
.hl-multiline-comment {
color: #3F5FBF;
font-style: italic;
color: #3F5FBF;
font-style: italic;
}
.hl-tag {
color: #3F7F7F;
color: #3F7F7F;
}
.hl-attribute {
color: #7F007F;
color: #7F007F;
}
.hl-value {
color: #2A00FF;
color: #2A00FF;
}
.hl-string {
color: #2A00FF;
color: #2A00FF;
}

View File

@ -1,112 +1,117 @@
/*
borrowed from: https://raw.github.com/SpringSource/spring-data-jpa/master/src/docbkx/resources/css/html.css
*/
@IMPORT url("highlight.css");
html {
padding: 0pt;
margin: 0pt;
padding: 0pt;
margin: 0pt;
}
body {
margin-left: 15%;
margin-right: 15%;
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
margin-left: 15%;
margin-right: 15%;
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande",
sans-serif;
}
div {
margin: 0pt;
margin: 0pt;
}
p {
text-align: justify;
line-height: 1.3em;
text-align: justify;
line-height: 1.3em;
}
hr {
border: 1px solid gray;
background: gray;
border: 1px solid gray;
background: gray;
}
h1,h2,h3,h4,h5 {
color: #234623;
font-weight: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
margin-bottom: 0em;
margin-top: 2em;
color: #234623;
font-weight: "Helvetica Neue", Helvetica, Arial, "Lucida Grande",
sans-serif;
margin-bottom: 0em;
margin-top: 2em;
}
pre {
line-height: 1.0;
color: black;
line-height: 1.0;
color: black;
}
table code {
font-size: 110%;
font-size: 110%;
}
pre.programlisting {
font-size: 1em;
padding: 3pt 3pt;
border: 1pt solid black;
background: #eeeeee;
clear: both;
font-size: 1em;
padding: 3pt 3pt;
border: 1pt solid black;
background: #eeeeee;
clear: both;
}
div.table {
margin: 1em;
padding: 0.5em;
text-align: center;
margin: 1em;
padding: 0.5em;
text-align: center;
}
div.table table {
display: table;
width: 100%;
display: table;
width: 100%;
}
div.table td {
padding-left: 7px;
padding-right: 7px;
padding-left: 7px;
padding-right: 7px;
}
.sidebar {
float: right;
margin: 10px 0 10px 30px;
padding: 10px 20px 20px 20px;
width: 33%;
border: 1px solid black;
background-color: #F4F4F4;
font-size: 14px;
float: right;
margin: 10px 0 10px 30px;
padding: 10px 20px 20px 20px;
width: 33%;
border: 1px solid black;
background-color: #F4F4F4;
font-size: 14px;
}
.mediaobject {
padding-top: 30px;
padding-bottom: 30px;
padding-top: 30px;
padding-bottom: 30px;
}
.legalnotice {
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-size: 12px;
font-style: italic;
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande",
sans-serif;
font-size: 12px;
font-style: italic;
}
p.releaseinfo {
font-size: 100%;
font-weight: bold;
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
padding-top: 10px;
font-size: 100%;
font-weight: bold;
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande",
sans-serif;
padding-top: 10px;
}
p.pubdate {
font-size: 120%;
font-weight: bold;
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-size: 120%;
font-weight: bold;
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande",
sans-serif;
}
span.productname {
font-size: 200%;
font-weight: bold;
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif;
font-size: 200%;
font-weight: bold;
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande",
sans-serif;
}
code {

View File

@ -1,433 +1,480 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
borrowed from: https://raw.github.com/SpringSource/spring-data-commons/master/src/docbkx/resources/xsl/fopdf.xsl
This is the XSL FO (PDF) stylesheet for the Spring Data reference
documentation.
-->
<!-- borrowed from: https://raw.github.com/SpringSource/spring-data-commons/master/src/docbkx/resources/xsl/fopdf.xsl
This is the XSL FO (PDF) stylesheet for the Spring Data reference documentation. -->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
version="1.0">
xmlns:fo="http://www.w3.org/1999/XSL/Format" version="1.0">
<xsl:import href="urn:docbkx:stylesheet"/>
<xsl:import href="highlight-fo.xsl"/>
<xsl:import href="urn:docbkx:stylesheet" />
<xsl:import href="highlight-fo.xsl" />
<!--###################################################
Custom Title Page
################################################### -->
<!--################################################### Custom Title Page
################################################### -->
<xsl:template name="book.titlepage.recto">
<fo:block>
<fo:table table-layout="fixed" width="175mm">
<fo:table-column column-width="175mm"/>
<fo:table-body>
<fo:table-row>
<fo:table-cell text-align="center">
<fo:block font-family="Helvetica" font-size="22pt" padding-before="10mm">
<xsl:value-of select="bookinfo/subtitle"/>
</fo:block>
<fo:block font-family="Helvetica" font-size="14pt" padding="10mm">
<xsl:value-of select="bookinfo/title"/>
</fo:block>
<fo:block font-family="Helvetica" font-size="12pt" padding="10mm">
<xsl:value-of select="bookinfo/releaseinfo"/>
</fo:block>
</fo:table-cell>
</fo:table-row>
<fo:table-row>
<fo:table-cell text-align="center">
<fo:block font-family="Helvetica" font-size="14pt" padding="10mm">
<xsl:value-of select="bookinfo/pubdate"/>
</fo:block>
</fo:table-cell>
</fo:table-row>
<fo:table-row>
<fo:table-cell text-align="center">
<fo:block font-family="Helvetica" font-size="12pt" padding="10mm">
<xsl:for-each select="bookinfo/authorgroup/author">
<xsl:if test="position() > 1">
<xsl:text>, </xsl:text>
</xsl:if>
<xsl:value-of select="firstname"/>
<xsl:text> </xsl:text>
<xsl:value-of select="surname"/>
<!-- <xsl:text> (</xsl:text>
<xsl:value-of select="affiliation"/>
<xsl:text>)</xsl:text> -->
</xsl:for-each>
</fo:block>
<fo:block font-family="Helvetica" font-size="12pt" padding="10mm">
<xsl:template name="book.titlepage.recto">
<fo:block>
<fo:table table-layout="fixed" width="175mm">
<fo:table-column column-width="175mm" />
<fo:table-body>
<fo:table-row>
<fo:table-cell text-align="center">
<fo:block font-family="Helvetica" font-size="22pt"
padding-before="10mm">
<xsl:value-of select="bookinfo/subtitle" />
</fo:block>
<fo:block font-family="Helvetica" font-size="14pt"
padding="10mm">
<xsl:value-of select="bookinfo/title" />
</fo:block>
<fo:block font-family="Helvetica" font-size="12pt"
padding="10mm">
<xsl:value-of select="bookinfo/releaseinfo" />
</fo:block>
</fo:table-cell>
</fo:table-row>
<fo:table-row>
<fo:table-cell text-align="center">
<fo:block font-family="Helvetica" font-size="14pt"
padding="10mm">
<xsl:value-of select="bookinfo/pubdate" />
</fo:block>
</fo:table-cell>
</fo:table-row>
<fo:table-row>
<fo:table-cell text-align="center">
<fo:block font-family="Helvetica" font-size="12pt"
padding="10mm">
<xsl:for-each select="bookinfo/authorgroup/author">
<xsl:if test="position() > 1">
<xsl:text>, </xsl:text>
</xsl:if>
<xsl:value-of select="firstname" />
<xsl:text> </xsl:text>
<xsl:value-of select="surname" />
<!-- <xsl:text> (</xsl:text> <xsl:value-of select="affiliation"/>
<xsl:text>)</xsl:text> -->
</xsl:for-each>
</fo:block>
<fo:block font-family="Helvetica" font-size="12pt"
padding="10mm">
<xsl:text>Copyright &#xA9; 2013</xsl:text>
</fo:block>
<fo:block font-family="Helvetica" font-size="10pt" padding="1mm">
<xsl:value-of select="bookinfo/legalnotice"/>
</fo:block>
</fo:table-cell>
</fo:table-row>
</fo:table-body>
</fo:table>
</fo:block>
</xsl:template>
<fo:block font-family="Helvetica" font-size="10pt"
padding="1mm">
<xsl:value-of select="bookinfo/legalnotice" />
</fo:block>
</fo:table-cell>
</fo:table-row>
</fo:table-body>
</fo:table>
</fo:block>
</xsl:template>
<!-- Prevent blank pages in output -->
<xsl:template name="book.titlepage.before.verso">
</xsl:template>
<xsl:template name="book.titlepage.verso">
</xsl:template>
<xsl:template name="book.titlepage.separator">
</xsl:template>
<!-- Prevent blank pages in output -->
<xsl:template name="book.titlepage.before.verso">
</xsl:template>
<xsl:template name="book.titlepage.verso">
</xsl:template>
<xsl:template name="book.titlepage.separator">
</xsl:template>
<!--###################################################
Header
################################################### -->
<!--################################################### Header ################################################### -->
<!-- More space in the center header for long text -->
<xsl:attribute-set name="header.content.properties">
<xsl:attribute name="font-family">
<xsl:value-of select="$body.font.family"/>
<!-- More space in the center header for long text -->
<xsl:attribute-set name="header.content.properties">
<xsl:attribute name="font-family">
<xsl:value-of select="$body.font.family" />
</xsl:attribute>
<xsl:attribute name="margin-left">-5em</xsl:attribute>
<xsl:attribute name="margin-right">-5em</xsl:attribute>
</xsl:attribute-set>
<xsl:attribute name="margin-left">-5em</xsl:attribute>
<xsl:attribute name="margin-right">-5em</xsl:attribute>
</xsl:attribute-set>
<!--###################################################
Custom Footer
################################################### -->
<xsl:template name="footer.content">
<xsl:param name="pageclass" select="''"/>
<xsl:param name="sequence" select="''"/>
<xsl:param name="position" select="''"/>
<xsl:param name="gentext-key" select="''"/>
<!--################################################### Custom Footer ################################################### -->
<xsl:template name="footer.content">
<xsl:param name="pageclass" select="''" />
<xsl:param name="sequence" select="''" />
<xsl:param name="position" select="''" />
<xsl:param name="gentext-key" select="''" />
<xsl:variable name="Version">
<xsl:if test="//releaseinfo">
<xsl:text>Spring Data Elasticsearch (</xsl:text><xsl:value-of select="//releaseinfo" /><xsl:text>)</xsl:text>
<xsl:text>Spring Data Elasticsearch (</xsl:text>
<xsl:value-of select="//releaseinfo" />
<xsl:text>)</xsl:text>
</xsl:if>
</xsl:variable>
<xsl:choose>
<xsl:when test="$sequence='blank'">
<xsl:if test="$position = 'center'">
<xsl:value-of select="$Version"/>
</xsl:if>
</xsl:when>
<!-- for double sided printing, print page numbers on alternating sides (of the page) -->
<xsl:when test="$double.sided != 0">
<xsl:choose>
<xsl:when test="$sequence = 'even' and $position='left'">
<fo:page-number/>
</xsl:when>
<xsl:when test="$sequence = 'odd' and $position='right'">
<fo:page-number/>
</xsl:when>
<xsl:when test="$position='center'">
<xsl:value-of select="$Version"/>
</xsl:when>
</xsl:choose>
</xsl:when>
<!-- for single sided printing, print all page numbers on the right (of the page) -->
<xsl:when test="$double.sided = 0">
<xsl:choose>
<xsl:when test="$position='center'">
<xsl:value-of select="$Version"/>
</xsl:when>
<xsl:when test="$position='right'">
<fo:page-number/>
</xsl:when>
</xsl:choose>
</xsl:when>
</xsl:choose>
</xsl:template>
<xsl:choose>
<xsl:when test="$sequence='blank'">
<xsl:if test="$position = 'center'">
<xsl:value-of select="$Version" />
</xsl:if>
</xsl:when>
<!-- for double sided printing, print page numbers on alternating sides
(of the page) -->
<xsl:when test="$double.sided != 0">
<xsl:choose>
<xsl:when test="$sequence = 'even' and $position='left'">
<fo:page-number />
</xsl:when>
<xsl:when test="$sequence = 'odd' and $position='right'">
<fo:page-number />
</xsl:when>
<xsl:when test="$position='center'">
<xsl:value-of select="$Version" />
</xsl:when>
</xsl:choose>
</xsl:when>
<!-- for single sided printing, print all page numbers on the right (of
the page) -->
<xsl:when test="$double.sided = 0">
<xsl:choose>
<xsl:when test="$position='center'">
<xsl:value-of select="$Version" />
</xsl:when>
<xsl:when test="$position='right'">
<fo:page-number />
</xsl:when>
</xsl:choose>
</xsl:when>
</xsl:choose>
</xsl:template>
<!--###################################################
Extensions
################################################### -->
<!--################################################### Extensions ################################################### -->
<!-- These extensions are required for table printing and other stuff -->
<xsl:param name="tablecolumns.extension">0</xsl:param>
<!-- FOP provide only PDF Bookmarks at the moment -->
<xsl:param name="fop.extensions">1</xsl:param>
<xsl:param name="fop1.extensions">1</xsl:param>
<xsl:param name="ignore.image.scaling">0</xsl:param>
<!-- These extensions are required for table printing and other stuff -->
<xsl:param name="tablecolumns.extension">
0
</xsl:param>
<!-- FOP provide only PDF Bookmarks at the moment -->
<xsl:param name="fop.extensions">
1
</xsl:param>
<xsl:param name="fop1.extensions">
1
</xsl:param>
<xsl:param name="ignore.image.scaling">
0
</xsl:param>
<!--###################################################
Table Of Contents
################################################### -->
<!--################################################### Table Of Contents
################################################### -->
<!-- Generate the TOCs for named components only -->
<xsl:param name="generate.toc">
book toc
</xsl:param>
<!-- Generate the TOCs for named components only -->
<xsl:param name="generate.toc">
book toc
</xsl:param>
<!-- Show only Sections up to level 3 in the TOCs -->
<xsl:param name="toc.section.depth">2</xsl:param>
<!-- Show only Sections up to level 3 in the TOCs -->
<xsl:param name="toc.section.depth">
2
</xsl:param>
<!-- Dot and Whitespace as separator in TOC between Label and Title-->
<xsl:param name="autotoc.label.separator" select="'. '"/>
<!-- Dot and Whitespace as separator in TOC between Label and Title -->
<xsl:param name="autotoc.label.separator" select="'. '" />
<!--###################################################
Paper & Page Size
################################################### -->
<!--################################################### Paper & Page Size
################################################### -->
<!-- Paper type, no headers on blank pages, no double sided printing -->
<xsl:param name="paper.type" select="'A4'"/>
<xsl:param name="double.sided">0</xsl:param>
<xsl:param name="headers.on.blank.pages">0</xsl:param>
<xsl:param name="footers.on.blank.pages">0</xsl:param>
<!-- Paper type, no headers on blank pages, no double sided printing -->
<xsl:param name="paper.type" select="'A4'" />
<xsl:param name="double.sided">
0
</xsl:param>
<xsl:param name="headers.on.blank.pages">
0
</xsl:param>
<xsl:param name="footers.on.blank.pages">
0
</xsl:param>
<!-- Space between paper border and content (chaotic stuff, don't touch) -->
<xsl:param name="page.margin.top">5mm</xsl:param>
<xsl:param name="region.before.extent">10mm</xsl:param>
<xsl:param name="body.margin.top">10mm</xsl:param>
<!-- Space between paper border and content (chaotic stuff, don't touch) -->
<xsl:param name="page.margin.top">
5mm
</xsl:param>
<xsl:param name="region.before.extent">
10mm
</xsl:param>
<xsl:param name="body.margin.top">
10mm
</xsl:param>
<xsl:param name="body.margin.bottom">15mm</xsl:param>
<xsl:param name="region.after.extent">10mm</xsl:param>
<xsl:param name="page.margin.bottom">0mm</xsl:param>
<xsl:param name="body.margin.bottom">
15mm
</xsl:param>
<xsl:param name="region.after.extent">
10mm
</xsl:param>
<xsl:param name="page.margin.bottom">
0mm
</xsl:param>
<xsl:param name="page.margin.outer">18mm</xsl:param>
<xsl:param name="page.margin.inner">18mm</xsl:param>
<xsl:param name="page.margin.outer">
18mm
</xsl:param>
<xsl:param name="page.margin.inner">
18mm
</xsl:param>
<!-- No intendation of Titles -->
<xsl:param name="title.margin.left">0pc</xsl:param>
<!-- No intendation of Titles -->
<xsl:param name="title.margin.left">
0pc
</xsl:param>
<!--###################################################
Fonts & Styles
################################################### -->
<!--################################################### Fonts & Styles ################################################### -->
<!-- Left aligned text and no hyphenation -->
<xsl:param name="alignment">justify</xsl:param>
<xsl:param name="hyphenate">false</xsl:param>
<!-- Left aligned text and no hyphenation -->
<xsl:param name="alignment">
justify
</xsl:param>
<xsl:param name="hyphenate">
false
</xsl:param>
<!-- Default Font size -->
<xsl:param name="body.font.master">11</xsl:param>
<xsl:param name="body.font.small">8</xsl:param>
<!-- Default Font size -->
<xsl:param name="body.font.master">
11
</xsl:param>
<xsl:param name="body.font.small">
8
</xsl:param>
<!-- Line height in body text -->
<xsl:param name="line-height">1.4</xsl:param>
<!-- Line height in body text -->
<xsl:param name="line-height">
1.4
</xsl:param>
<!-- Monospaced fonts are smaller than regular text -->
<xsl:attribute-set name="monospace.properties">
<xsl:attribute name="font-family">
<xsl:value-of select="$monospace.font.family"/>
<!-- Monospaced fonts are smaller than regular text -->
<xsl:attribute-set name="monospace.properties">
<xsl:attribute name="font-family">
<xsl:value-of select="$monospace.font.family" />
</xsl:attribute>
<xsl:attribute name="font-size">0.8em</xsl:attribute>
</xsl:attribute-set>
<xsl:attribute name="font-size">0.8em</xsl:attribute>
</xsl:attribute-set>
<!--###################################################
Tables
################################################### -->
<!--################################################### Tables ################################################### -->
<!-- The table width should be adapted to the paper size -->
<xsl:param name="default.table.width">17.4cm</xsl:param>
<!-- The table width should be adapted to the paper size -->
<xsl:param name="default.table.width">
17.4cm
</xsl:param>
<!-- Some padding inside tables -->
<xsl:attribute-set name="table.cell.padding">
<xsl:attribute name="padding-left">4pt</xsl:attribute>
<xsl:attribute name="padding-right">4pt</xsl:attribute>
<xsl:attribute name="padding-top">4pt</xsl:attribute>
<xsl:attribute name="padding-bottom">4pt</xsl:attribute>
</xsl:attribute-set>
<!-- Some padding inside tables -->
<xsl:attribute-set name="table.cell.padding">
<xsl:attribute name="padding-left">4pt</xsl:attribute>
<xsl:attribute name="padding-right">4pt</xsl:attribute>
<xsl:attribute name="padding-top">4pt</xsl:attribute>
<xsl:attribute name="padding-bottom">4pt</xsl:attribute>
</xsl:attribute-set>
<!-- Only hairlines as frame and cell borders in tables -->
<xsl:param name="table.frame.border.thickness">0.1pt</xsl:param>
<xsl:param name="table.cell.border.thickness">0.1pt</xsl:param>
<!-- Only hairlines as frame and cell borders in tables -->
<xsl:param name="table.frame.border.thickness">
0.1pt
</xsl:param>
<xsl:param name="table.cell.border.thickness">
0.1pt
</xsl:param>
<!--###################################################
Labels
################################################### -->
<!--################################################### Labels ################################################### -->
<!-- Label Chapters and Sections (numbering) -->
<xsl:param name="chapter.autolabel">1</xsl:param>
<xsl:param name="section.autolabel" select="1"/>
<xsl:param name="section.label.includes.component.label" select="1"/>
<!-- Label Chapters and Sections (numbering) -->
<xsl:param name="chapter.autolabel">
1
</xsl:param>
<xsl:param name="section.autolabel" select="1" />
<xsl:param name="section.label.includes.component.label"
select="1" />
<!--###################################################
Titles
################################################### -->
<!--################################################### Titles ################################################### -->
<!-- Chapter title size -->
<xsl:attribute-set name="chapter.titlepage.recto.style">
<xsl:attribute name="text-align">left</xsl:attribute>
<xsl:attribute name="font-weight">bold</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master * 1.8"/>
<!-- Chapter title size -->
<xsl:attribute-set name="chapter.titlepage.recto.style">
<xsl:attribute name="text-align">left</xsl:attribute>
<xsl:attribute name="font-weight">bold</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master * 1.8" />
<xsl:text>pt</xsl:text>
</xsl:attribute>
</xsl:attribute-set>
</xsl:attribute-set>
<!-- Why is the font-size for chapters hardcoded in the XSL FO templates?
Let's remove it, so this sucker can use our attribute-set only... -->
<xsl:template match="title" mode="chapter.titlepage.recto.auto.mode">
<fo:block xmlns:fo="http://www.w3.org/1999/XSL/Format"
xsl:use-attribute-sets="chapter.titlepage.recto.style">
<xsl:call-template name="component.title">
<xsl:with-param name="node" select="ancestor-or-self::chapter[1]"/>
</xsl:call-template>
</fo:block>
</xsl:template>
<!-- Why is the font-size for chapters hardcoded in the XSL FO templates?
Let's remove it, so this sucker can use our attribute-set only... -->
<xsl:template match="title" mode="chapter.titlepage.recto.auto.mode">
<fo:block xmlns:fo="http://www.w3.org/1999/XSL/Format"
xsl:use-attribute-sets="chapter.titlepage.recto.style">
<xsl:call-template name="component.title">
<xsl:with-param name="node" select="ancestor-or-self::chapter[1]" />
</xsl:call-template>
</fo:block>
</xsl:template>
<!-- Sections 1, 2 and 3 titles have a small bump factor and padding -->
<xsl:attribute-set name="section.title.level1.properties">
<xsl:attribute name="space-before.optimum">0.8em</xsl:attribute>
<xsl:attribute name="space-before.minimum">0.8em</xsl:attribute>
<xsl:attribute name="space-before.maximum">0.8em</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master * 1.5"/>
<!-- Sections 1, 2 and 3 titles have a small bump factor and padding -->
<xsl:attribute-set name="section.title.level1.properties">
<xsl:attribute name="space-before.optimum">0.8em</xsl:attribute>
<xsl:attribute name="space-before.minimum">0.8em</xsl:attribute>
<xsl:attribute name="space-before.maximum">0.8em</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master * 1.5" />
<xsl:text>pt</xsl:text>
</xsl:attribute>
<xsl:attribute name="space-after.optimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.1em</xsl:attribute>
</xsl:attribute-set>
<xsl:attribute-set name="section.title.level2.properties">
<xsl:attribute name="space-before.optimum">0.6em</xsl:attribute>
<xsl:attribute name="space-before.minimum">0.6em</xsl:attribute>
<xsl:attribute name="space-before.maximum">0.6em</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master * 1.25"/>
<xsl:attribute name="space-after.optimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.1em</xsl:attribute>
</xsl:attribute-set>
<xsl:attribute-set name="section.title.level2.properties">
<xsl:attribute name="space-before.optimum">0.6em</xsl:attribute>
<xsl:attribute name="space-before.minimum">0.6em</xsl:attribute>
<xsl:attribute name="space-before.maximum">0.6em</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master * 1.25" />
<xsl:text>pt</xsl:text>
</xsl:attribute>
<xsl:attribute name="space-after.optimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.1em</xsl:attribute>
</xsl:attribute-set>
<xsl:attribute-set name="section.title.level3.properties">
<xsl:attribute name="space-before.optimum">0.4em</xsl:attribute>
<xsl:attribute name="space-before.minimum">0.4em</xsl:attribute>
<xsl:attribute name="space-before.maximum">0.4em</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master * 1.0"/>
<xsl:attribute name="space-after.optimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.1em</xsl:attribute>
</xsl:attribute-set>
<xsl:attribute-set name="section.title.level3.properties">
<xsl:attribute name="space-before.optimum">0.4em</xsl:attribute>
<xsl:attribute name="space-before.minimum">0.4em</xsl:attribute>
<xsl:attribute name="space-before.maximum">0.4em</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master * 1.0" />
<xsl:text>pt</xsl:text>
</xsl:attribute>
<xsl:attribute name="space-after.optimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.1em</xsl:attribute>
</xsl:attribute-set>
<xsl:attribute name="space-after.optimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.1em</xsl:attribute>
</xsl:attribute-set>
<!-- Titles of formal objects (tables, examples, ...) -->
<xsl:attribute-set name="formal.title.properties" use-attribute-sets="normal.para.spacing">
<xsl:attribute name="font-weight">bold</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master"/>
<!-- Titles of formal objects (tables, examples, ...) -->
<xsl:attribute-set name="formal.title.properties"
use-attribute-sets="normal.para.spacing">
<xsl:attribute name="font-weight">bold</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master" />
<xsl:text>pt</xsl:text>
</xsl:attribute>
<xsl:attribute name="hyphenate">false</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.4em</xsl:attribute>
<xsl:attribute name="space-after.optimum">0.6em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.8em</xsl:attribute>
</xsl:attribute-set>
<xsl:attribute name="hyphenate">false</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.4em</xsl:attribute>
<xsl:attribute name="space-after.optimum">0.6em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.8em</xsl:attribute>
</xsl:attribute-set>
<!--###################################################
Programlistings
################################################### -->
<!--################################################### Programlistings
################################################### -->
<!-- Verbatim text formatting (programlistings) -->
<xsl:attribute-set name="monospace.verbatim.properties">
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.small * 1.0"/>
<!-- Verbatim text formatting (programlistings) -->
<xsl:attribute-set name="monospace.verbatim.properties">
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.small * 1.0" />
<xsl:text>pt</xsl:text>
</xsl:attribute>
</xsl:attribute-set>
</xsl:attribute-set>
<xsl:attribute-set name="verbatim.properties">
<xsl:attribute name="space-before.minimum">1em</xsl:attribute>
<xsl:attribute name="space-before.optimum">1em</xsl:attribute>
<xsl:attribute name="space-before.maximum">1em</xsl:attribute>
<xsl:attribute name="border-color">#444444</xsl:attribute>
<xsl:attribute name="border-style">solid</xsl:attribute>
<xsl:attribute name="border-width">0.1pt</xsl:attribute>
<xsl:attribute name="padding-top">0.5em</xsl:attribute>
<xsl:attribute name="padding-left">0.5em</xsl:attribute>
<xsl:attribute name="padding-right">0.5em</xsl:attribute>
<xsl:attribute name="padding-bottom">0.5em</xsl:attribute>
<xsl:attribute name="margin-left">0.5em</xsl:attribute>
<xsl:attribute name="margin-right">0.5em</xsl:attribute>
</xsl:attribute-set>
<xsl:attribute-set name="verbatim.properties">
<xsl:attribute name="space-before.minimum">1em</xsl:attribute>
<xsl:attribute name="space-before.optimum">1em</xsl:attribute>
<xsl:attribute name="space-before.maximum">1em</xsl:attribute>
<xsl:attribute name="border-color">#444444</xsl:attribute>
<xsl:attribute name="border-style">solid</xsl:attribute>
<xsl:attribute name="border-width">0.1pt</xsl:attribute>
<xsl:attribute name="padding-top">0.5em</xsl:attribute>
<xsl:attribute name="padding-left">0.5em</xsl:attribute>
<xsl:attribute name="padding-right">0.5em</xsl:attribute>
<xsl:attribute name="padding-bottom">0.5em</xsl:attribute>
<xsl:attribute name="margin-left">0.5em</xsl:attribute>
<xsl:attribute name="margin-right">0.5em</xsl:attribute>
</xsl:attribute-set>
<!-- Shade (background) programlistings -->
<xsl:param name="shade.verbatim">1</xsl:param>
<xsl:attribute-set name="shade.verbatim.style">
<xsl:attribute name="background-color">#F0F0F0</xsl:attribute>
</xsl:attribute-set>
<!-- Shade (background) programlistings -->
<xsl:param name="shade.verbatim">
1
</xsl:param>
<xsl:attribute-set name="shade.verbatim.style">
<xsl:attribute name="background-color">#F0F0F0</xsl:attribute>
</xsl:attribute-set>
<!--###################################################
Callouts
################################################### -->
<!--################################################### Callouts ################################################### -->
<!-- Use images for callouts instead of (1) (2) (3) -->
<xsl:param name="callout.graphics">0</xsl:param>
<xsl:param name="callout.unicode">1</xsl:param>
<!-- Use images for callouts instead of (1) (2) (3) -->
<xsl:param name="callout.graphics">
0
</xsl:param>
<xsl:param name="callout.unicode">
1
</xsl:param>
<!-- Place callout marks at this column in annotated areas -->
<xsl:param name="callout.defaultcolumn">90</xsl:param>
<!-- Place callout marks at this column in annotated areas -->
<xsl:param name="callout.defaultcolumn">
90
</xsl:param>
<!--###################################################
Admonitions
################################################### -->
<!--################################################### Admonitions ################################################### -->
<!-- Use nice graphics for admonitions -->
<xsl:param name="admon.graphics">'1'</xsl:param>
<xsl:param name="admon.graphics.path">src/docbkx/resources/images/admons/</xsl:param>
<!-- Use nice graphics for admonitions -->
<xsl:param name="admon.graphics">
'1'
</xsl:param>
<xsl:param name="admon.graphics.path">
src/docbkx/resources/images/admons/
</xsl:param>
<!--###################################################
Misc
################################################### -->
<!--################################################### Misc ################################################### -->
<!-- Placement of titles -->
<xsl:param name="formal.title.placement">
figure after
example before
equation before
table before
procedure before
</xsl:param>
<!-- Placement of titles -->
<xsl:param name="formal.title.placement">
figure after
example before
equation before
table before
procedure before
</xsl:param>
<!-- Format Variable Lists as Blocks (prevents horizontal overflow) -->
<xsl:param name="variablelist.as.blocks">1</xsl:param>
<!-- Format Variable Lists as Blocks (prevents horizontal overflow) -->
<xsl:param name="variablelist.as.blocks">
1
</xsl:param>
<!-- The horrible list spacing problems -->
<xsl:attribute-set name="list.block.spacing">
<xsl:attribute name="space-before.optimum">0.8em</xsl:attribute>
<xsl:attribute name="space-before.minimum">0.8em</xsl:attribute>
<xsl:attribute name="space-before.maximum">0.8em</xsl:attribute>
<xsl:attribute name="space-after.optimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.1em</xsl:attribute>
</xsl:attribute-set>
<!-- The horrible list spacing problems -->
<xsl:attribute-set name="list.block.spacing">
<xsl:attribute name="space-before.optimum">0.8em</xsl:attribute>
<xsl:attribute name="space-before.minimum">0.8em</xsl:attribute>
<xsl:attribute name="space-before.maximum">0.8em</xsl:attribute>
<xsl:attribute name="space-after.optimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.1em</xsl:attribute>
</xsl:attribute-set>
<!--###################################################
colored and hyphenated links
################################################### -->
<xsl:template match="ulink">
<fo:basic-link external-destination="{@url}"
xsl:use-attribute-sets="xref.properties"
text-decoration="underline"
color="blue">
<xsl:choose>
<xsl:when test="count(child::node())=0">
<xsl:value-of select="@url"/>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates/>
</xsl:otherwise>
</xsl:choose>
</fo:basic-link>
</xsl:template>
<!--################################################### colored and hyphenated
links ################################################### -->
<xsl:template match="ulink">
<fo:basic-link external-destination="{@url}"
xsl:use-attribute-sets="xref.properties" text-decoration="underline"
color="blue">
<xsl:choose>
<xsl:when test="count(child::node())=0">
<xsl:value-of select="@url" />
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates />
</xsl:otherwise>
</xsl:choose>
</fo:basic-link>
</xsl:template>
<xsl:template match="link">
<fo:basic-link internal-destination="{@linkend}"
xsl:use-attribute-sets="xref.properties"
text-decoration="underline"
color="blue">
<xsl:choose>
<xsl:when test="count(child::node())=0">
<xsl:value-of select="@linkend"/>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates/>
</xsl:otherwise>
</xsl:choose>
</fo:basic-link>
</xsl:template>
<xsl:template match="link">
<fo:basic-link internal-destination="{@linkend}"
xsl:use-attribute-sets="xref.properties" text-decoration="underline"
color="blue">
<xsl:choose>
<xsl:when test="count(child::node())=0">
<xsl:value-of select="@linkend" />
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates />
</xsl:otherwise>
</xsl:choose>
</fo:basic-link>
</xsl:template>
</xsl:stylesheet>

View File

@ -1,45 +1,57 @@
<?xml version='1.0'?>
<!--
borrowed from: https://raw.github.com/SpringSource/spring-data-jpa/master/src/docbkx/resources/xsl/highlight-fo.xsl
Simple highlighter for FO/PDF output. Follows the Eclipse color scheme.
-->
<!-- borrowed from: https://raw.github.com/SpringSource/spring-data-jpa/master/src/docbkx/resources/xsl/highlight-fo.xsl
Simple highlighter for FO/PDF output. Follows the Eclipse color scheme. -->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
xmlns:xslthl="http://xslthl.sf.net"
exclude-result-prefixes="xslthl"
version='1.0'>
xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xslthl="http://xslthl.sf.net"
exclude-result-prefixes="xslthl" version='1.0'>
<xsl:template match='xslthl:keyword'>
<fo:inline font-weight="bold" color="#7F0055"><xsl:apply-templates/></fo:inline>
<fo:inline font-weight="bold" color="#7F0055">
<xsl:apply-templates />
</fo:inline>
</xsl:template>
<xsl:template match='xslthl:comment'>
<fo:inline font-style="italic" color="#3F5F5F"><xsl:apply-templates/></fo:inline>
<fo:inline font-style="italic" color="#3F5F5F">
<xsl:apply-templates />
</fo:inline>
</xsl:template>
<xsl:template match='xslthl:oneline-comment'>
<fo:inline font-style="italic" color="#3F5F5F"><xsl:apply-templates/></fo:inline>
<fo:inline font-style="italic" color="#3F5F5F">
<xsl:apply-templates />
</fo:inline>
</xsl:template>
<xsl:template match='xslthl:multiline-comment'>
<fo:inline font-style="italic" color="#3F5FBF"><xsl:apply-templates/></fo:inline>
<fo:inline font-style="italic" color="#3F5FBF">
<xsl:apply-templates />
</fo:inline>
</xsl:template>
<xsl:template match='xslthl:tag'>
<fo:inline color="#3F7F7F"><xsl:apply-templates/></fo:inline>
<fo:inline color="#3F7F7F">
<xsl:apply-templates />
</fo:inline>
</xsl:template>
<xsl:template match='xslthl:attribute'>
<fo:inline color="#7F007F"><xsl:apply-templates/></fo:inline>
<fo:inline color="#7F007F">
<xsl:apply-templates />
</fo:inline>
</xsl:template>
<xsl:template match='xslthl:value'>
<fo:inline color="#2A00FF"><xsl:apply-templates/></fo:inline>
<fo:inline color="#2A00FF">
<xsl:apply-templates />
</fo:inline>
</xsl:template>
<xsl:template match='xslthl:string'>
<fo:inline color="#2A00FF"><xsl:apply-templates/></fo:inline>
<fo:inline color="#2A00FF">
<xsl:apply-templates />
</fo:inline>
</xsl:template>
</xsl:stylesheet>

View File

@ -1,43 +1,56 @@
<?xml version='1.0'?>
<!--
borrowed from: https://raw.github.com/SpringSource/spring-data-jpa/master/src/docbkx/resources/xsl/highlight.xsl
Simple highlighter for HTML output. Follows the Eclipse color scheme.
-->
<!-- borrowed from: https://raw.github.com/SpringSource/spring-data-jpa/master/src/docbkx/resources/xsl/highlight.xsl
Simple highlighter for HTML output. Follows the Eclipse color scheme. -->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:xslthl="http://xslthl.sf.net"
exclude-result-prefixes="xslthl"
version='1.0'>
xmlns:xslthl="http://xslthl.sf.net" exclude-result-prefixes="xslthl"
version='1.0'>
<xsl:template match='xslthl:keyword'>
<span class="hl-keyword"><xsl:value-of select='.'/></span>
<span class="hl-keyword">
<xsl:value-of select='.' />
</span>
</xsl:template>
<xsl:template match='xslthl:comment'>
<span class="hl-comment"><xsl:value-of select='.'/></span>
<span class="hl-comment">
<xsl:value-of select='.' />
</span>
</xsl:template>
<xsl:template match='xslthl:oneline-comment'>
<span class="hl-comment"><xsl:value-of select='.'/></span>
<span class="hl-comment">
<xsl:value-of select='.' />
</span>
</xsl:template>
<xsl:template match='xslthl:multiline-comment'>
<span class="hl-multiline-comment"><xsl:value-of select='.'/></span>
<span class="hl-multiline-comment">
<xsl:value-of select='.' />
</span>
</xsl:template>
<xsl:template match='xslthl:tag'>
<span class="hl-tag"><xsl:value-of select='.'/></span>
<span class="hl-tag">
<xsl:value-of select='.' />
</span>
</xsl:template>
<xsl:template match='xslthl:attribute'>
<span class="hl-attribute"><xsl:value-of select='.'/></span>
<span class="hl-attribute">
<xsl:value-of select='.' />
</span>
</xsl:template>
<xsl:template match='xslthl:value'>
<span class="hl-value"><xsl:value-of select='.'/></span>
<span class="hl-value">
<xsl:value-of select='.' />
</span>
</xsl:template>
<xsl:template match='xslthl:string'>
<span class="hl-string"><xsl:value-of select='.'/></span>
<span class="hl-string">
<xsl:value-of select='.' />
</span>
</xsl:template>
</xsl:stylesheet>

View File

@ -1,108 +1,114 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
borrowed from: https://raw.github.com/SpringSource/spring-data-jpa/master/src/docbkx/resources/xsl/html.xsl
This is the XSL HTML configuration file for the Spring
Reference Documentation.
-->
<!-- borrowed from: https://raw.github.com/SpringSource/spring-data-jpa/master/src/docbkx/resources/xsl/html.xsl
This is the XSL HTML configuration file for the Spring Reference Documentation. -->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
xmlns:xslthl="http://xslthl.sf.net"
exclude-result-prefixes="xslthl"
version="1.0">
xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xslthl="http://xslthl.sf.net"
exclude-result-prefixes="xslthl" version="1.0">
<xsl:import href="urn:docbkx:stylesheet"/>
<xsl:import href="highlight.xsl"/>
<xsl:import href="urn:docbkx:stylesheet" />
<xsl:import href="highlight.xsl" />
<!--###################################################
HTML Settings
################################################### -->
<!--################################################### HTML Settings ################################################### -->
<!-- These extensions are required for table printing and other stuff -->
<xsl:param name="tablecolumns.extension">0</xsl:param>
<xsl:param name="graphicsize.extension">0</xsl:param>
<xsl:param name="ignore.image.scaling">1</xsl:param>
<!-- These extensions are required for table printing and other stuff -->
<xsl:param name="tablecolumns.extension">
0
</xsl:param>
<xsl:param name="graphicsize.extension">
0
</xsl:param>
<xsl:param name="ignore.image.scaling">
1
</xsl:param>
<!--###################################################
Table Of Contents
################################################### -->
<!--################################################### Table Of Contents
################################################### -->
<!-- Generate the TOCs for named components only -->
<xsl:param name="generate.toc">
book toc
</xsl:param>
<!-- Generate the TOCs for named components only -->
<xsl:param name="generate.toc">
book toc
</xsl:param>
<!-- Show only Sections up to level 3 in the TOCs -->
<xsl:param name="toc.section.depth">3</xsl:param>
<!-- Show only Sections up to level 3 in the TOCs -->
<xsl:param name="toc.section.depth">
3
</xsl:param>
<!--###################################################
Labels
################################################### -->
<!--################################################### Labels ################################################### -->
<!-- Label Chapters and Sections (numbering) -->
<xsl:param name="chapter.autolabel">1</xsl:param>
<xsl:param name="section.autolabel" select="1"/>
<xsl:param name="section.label.includes.component.label" select="1"/>
<!-- Label Chapters and Sections (numbering) -->
<xsl:param name="chapter.autolabel">
1
</xsl:param>
<xsl:param name="section.autolabel" select="1" />
<xsl:param name="section.label.includes.component.label"
select="1" />
<!--###################################################
Callouts
################################################### -->
<!--################################################### Callouts ################################################### -->
<!-- Use images for callouts instead of (1) (2) (3) -->
<xsl:param name="callout.graphics">1</xsl:param>
<!-- Use images for callouts instead of (1) (2) (3) -->
<xsl:param name="callout.graphics">
1
</xsl:param>
<!-- Place callout marks at this column in annotated areas -->
<xsl:param name="callout.defaultcolumn">90</xsl:param>
<!-- Place callout marks at this column in annotated areas -->
<xsl:param name="callout.defaultcolumn">
90
</xsl:param>
<!--###################################################
Admonitions
################################################### -->
<!--################################################### Admonitions ################################################### -->
<!-- Use nice graphics for admonitions -->
<xsl:param name="admon.graphics">1</xsl:param>
<xsl:param name="admon.graphics.path">images/admons/</xsl:param>
<!--###################################################
Misc
################################################### -->
<!-- Placement of titles -->
<xsl:param name="formal.title.placement">
figure after
example before
equation before
table before
procedure before
</xsl:param>
<xsl:template match="author" mode="titlepage.mode">
<xsl:if test="name(preceding-sibling::*[1]) = 'author'">
<xsl:text>, </xsl:text>
</xsl:if>
<span class="{name(.)}">
<xsl:call-template name="person.name"/>
<!-- (<xsl:value-of select="affiliation"/>) -->
<xsl:apply-templates mode="titlepage.mode" select="./contrib"/>
</span>
</xsl:template>
<xsl:template match="authorgroup" mode="titlepage.mode">
<div class="{name(.)}">
<h2>Authors</h2>
<p/>
<xsl:apply-templates mode="titlepage.mode"/>
</div>
</xsl:template>
<!--###################################################
Headers and Footers
################################################### -->
<!-- let's have a Spring and I21 banner across the top of each page -->
<xsl:template name="user.header.navigation">
<div style="background-color:white;border:none;height:73px;border:1px solid black;">
<a style="border:none;" href="http://www.springframework.org/osgi/"
title="The Spring Framework - Spring Data">
<img style="border:none;" src="images/xdev-spring_logo.jpg"/>
</a>
<a style="border:none;" href="http://www.SpringSource.com/" title="SpringSource - Spring from the Source">
<img style="border:none;position:absolute;padding-top:5px;right:42px;" src="images/s2-banner-rhs.png"/>
</a>
</div>
</xsl:template>
<!-- Use nice graphics for admonitions -->
<xsl:param name="admon.graphics">
1
</xsl:param>
<xsl:param name="admon.graphics.path">
images/admons/
</xsl:param>
<!--################################################### Misc ################################################### -->
<!-- Placement of titles -->
<xsl:param name="formal.title.placement">
figure after
example before
equation before
table before
procedure before
</xsl:param>
<xsl:template match="author" mode="titlepage.mode">
<xsl:if test="name(preceding-sibling::*[1]) = 'author'">
<xsl:text>, </xsl:text>
</xsl:if>
<span class="{name(.)}">
<xsl:call-template name="person.name" />
<!-- (<xsl:value-of select="affiliation"/>) -->
<xsl:apply-templates mode="titlepage.mode"
select="./contrib" />
</span>
</xsl:template>
<xsl:template match="authorgroup" mode="titlepage.mode">
<div class="{name(.)}">
<h2>Authors</h2>
<p />
<xsl:apply-templates mode="titlepage.mode" />
</div>
</xsl:template>
<!--################################################### Headers and Footers
################################################### -->
<!-- let's have a Spring and I21 banner across the top of each page -->
<xsl:template name="user.header.navigation">
<div
style="background-color:white;border:none;height:73px;border:1px solid black;">
<a style="border:none;" href="http://www.springframework.org/osgi/"
title="The Spring Framework - Spring Data">
<img style="border:none;" src="images/xdev-spring_logo.jpg" />
</a>
<a style="border:none;" href="http://www.SpringSource.com/"
title="SpringSource - Spring from the Source">
<img style="border:none;position:absolute;padding-top:5px;right:42px;"
src="images/s2-banner-rhs.png" />
</a>
</div>
</xsl:template>
</xsl:stylesheet>

View File

@ -1,222 +1,253 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
borrowed from: https://raw.github.com/SpringSource/spring-data-jpa/master/src/docbkx/resources/xsl/html_chunk.xsl
This is the XSL HTML configuration file for the Spring Reference Documentation.
-->
<!-- borrowed from: https://raw.github.com/SpringSource/spring-data-jpa/master/src/docbkx/resources/xsl/html_chunk.xsl
This is the XSL HTML configuration file for the Spring Reference Documentation. -->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
version="1.0">
xmlns:fo="http://www.w3.org/1999/XSL/Format" version="1.0">
<xsl:import href="urn:docbkx:stylesheet"/>
<xsl:import href="highlight.xsl"/>
<xsl:import href="urn:docbkx:stylesheet" />
<xsl:import href="highlight.xsl" />
<!--###################################################
HTML Settings
################################################### -->
<xsl:param name="chunk.section.depth">'5'</xsl:param>
<xsl:param name="use.id.as.filename">'1'</xsl:param>
<xsl:param name="tablecolumns.extension">0</xsl:param>
<xsl:param name="graphicsize.extension">0</xsl:param>
<xsl:param name="ignore.image.scaling">1</xsl:param>
<!--###################################################
Table Of Contents
################################################### -->
<!-- Generate the TOCs for named components only -->
<xsl:param name="generate.toc">
book toc
qandaset toc
</xsl:param>
<!-- Show only Sections up to level 3 in the TOCs -->
<xsl:param name="toc.section.depth">3</xsl:param>
<!--###################################################
Labels
################################################### -->
<!-- Label Chapters and Sections (numbering) -->
<xsl:param name="chapter.autolabel">1</xsl:param>
<xsl:param name="section.autolabel" select="1"/>
<xsl:param name="section.label.includes.component.label" select="1"/>
<!--###################################################
Callouts
################################################### -->
<!-- Place callout marks at this column in annotated areas -->
<xsl:param name="callout.graphics">1</xsl:param>
<xsl:param name="callout.defaultcolumn">90</xsl:param>
<!--################################################### HTML Settings ################################################### -->
<xsl:param name="chunk.section.depth">
'5'
</xsl:param>
<xsl:param name="use.id.as.filename">
'1'
</xsl:param>
<xsl:param name="tablecolumns.extension">
0
</xsl:param>
<xsl:param name="graphicsize.extension">
0
</xsl:param>
<xsl:param name="ignore.image.scaling">
1
</xsl:param>
<!--################################################### Table Of Contents
################################################### -->
<!-- Generate the TOCs for named components only -->
<xsl:param name="generate.toc">
book toc
qandaset toc
</xsl:param>
<!-- Show only Sections up to level 3 in the TOCs -->
<xsl:param name="toc.section.depth">
3
</xsl:param>
<!--################################################### Labels ################################################### -->
<!-- Label Chapters and Sections (numbering) -->
<xsl:param name="chapter.autolabel">
1
</xsl:param>
<xsl:param name="section.autolabel" select="1" />
<xsl:param name="section.label.includes.component.label"
select="1" />
<!--################################################### Callouts ################################################### -->
<!-- Place callout marks at this column in annotated areas -->
<xsl:param name="callout.graphics">
1
</xsl:param>
<xsl:param name="callout.defaultcolumn">
90
</xsl:param>
<!--###################################################
Admonitions
################################################### -->
<!--################################################### Admonitions ################################################### -->
<!-- Use nice graphics for admonitions -->
<xsl:param name="admon.graphics">1</xsl:param>
<xsl:param name="admon.graphics.path">images/admons/</xsl:param>
<!--###################################################
Misc
################################################### -->
<!-- Placement of titles -->
<xsl:param name="formal.title.placement">
figure after
example before
equation before
table before
procedure before
</xsl:param>
<xsl:template match="author" mode="titlepage.mode">
<xsl:if test="name(preceding-sibling::*[1]) = 'author'">
<xsl:text>, </xsl:text>
</xsl:if>
<span class="{name(.)}">
<xsl:call-template name="person.name"/>
(<xsl:value-of select="affiliation"/>)
<xsl:apply-templates mode="titlepage.mode" select="./contrib"/>
<!--
<xsl:apply-templates mode="titlepage.mode" select="./affiliation"/>
-->
</span>
</xsl:template>
<xsl:template match="authorgroup" mode="titlepage.mode">
<div class="{name(.)}">
<h2>Authors</h2>
<p/>
<xsl:apply-templates mode="titlepage.mode"/>
</div>
</xsl:template>
<!--###################################################
Headers and Footers
################################################### -->
<!-- let's have a Spring and I21 banner across the top of each page -->
<xsl:template name="user.header.navigation">
<div style="background-color:white;border:none;height:73px;border:1px solid black;">
<a style="border:none;" href="http://www.springframework.org/osgi/"
title="The Spring Framework - Spring Data">
<img style="border:none;" src="images/xdev-spring_logo.jpg"/>
</a>
<a style="border:none;" href="http://www.SpringSource.com/" title="SpringSource - Spring from the Source">
<img style="border:none;position:absolute;padding-top:5px;right:42px;" src="images/s2-banner-rhs.png"/>
</a>
</div>
</xsl:template>
<!-- no other header navigation (prev, next, etc.) -->
<xsl:template name="header.navigation"/>
<xsl:param name="navig.showtitles">1</xsl:param>
<!-- let's have a 'Sponsored by SpringSource' strapline (or somesuch) across the bottom of each page -->
<xsl:template name="footer.navigation">
<xsl:param name="prev" select="/foo"/>
<xsl:param name="next" select="/foo"/>
<xsl:param name="nav.context"/>
<xsl:variable name="home" select="/*[1]"/>
<xsl:variable name="up" select="parent::*"/>
<xsl:variable name="row1" select="count($prev) &gt; 0
<!-- Use nice graphics for admonitions -->
<xsl:param name="admon.graphics">
1
</xsl:param>
<xsl:param name="admon.graphics.path">
images/admons/
</xsl:param>
<!--################################################### Misc ################################################### -->
<!-- Placement of titles -->
<xsl:param name="formal.title.placement">
figure after
example before
equation before
table before
procedure before
</xsl:param>
<xsl:template match="author" mode="titlepage.mode">
<xsl:if test="name(preceding-sibling::*[1]) = 'author'">
<xsl:text>, </xsl:text>
</xsl:if>
<span class="{name(.)}">
<xsl:call-template name="person.name" />
(
<xsl:value-of select="affiliation" />
)
<xsl:apply-templates mode="titlepage.mode"
select="./contrib" />
<!-- <xsl:apply-templates mode="titlepage.mode" select="./affiliation"/> -->
</span>
</xsl:template>
<xsl:template match="authorgroup" mode="titlepage.mode">
<div class="{name(.)}">
<h2>Authors</h2>
<p />
<xsl:apply-templates mode="titlepage.mode" />
</div>
</xsl:template>
<!--################################################### Headers and Footers
################################################### -->
<!-- let's have a Spring and I21 banner across the top of each page -->
<xsl:template name="user.header.navigation">
<div
style="background-color:white;border:none;height:73px;border:1px solid black;">
<a style="border:none;" href="http://www.springframework.org/osgi/"
title="The Spring Framework - Spring Data">
<img style="border:none;" src="images/xdev-spring_logo.jpg" />
</a>
<a style="border:none;" href="http://www.SpringSource.com/"
title="SpringSource - Spring from the Source">
<img style="border:none;position:absolute;padding-top:5px;right:42px;"
src="images/s2-banner-rhs.png" />
</a>
</div>
</xsl:template>
<!-- no other header navigation (prev, next, etc.) -->
<xsl:template name="header.navigation" />
<xsl:param name="navig.showtitles">
1
</xsl:param>
<!-- let's have a 'Sponsored by SpringSource' strapline (or somesuch) across
the bottom of each page -->
<xsl:template name="footer.navigation">
<xsl:param name="prev" select="/foo" />
<xsl:param name="next" select="/foo" />
<xsl:param name="nav.context" />
<xsl:variable name="home" select="/*[1]" />
<xsl:variable name="up" select="parent::*" />
<xsl:variable name="row1"
select="count($prev) &gt; 0
or count($up) &gt; 0
or count($next) &gt; 0"/>
<xsl:variable name="row2" select="($prev and $navig.showtitles != 0)
or count($next) &gt; 0" />
<xsl:variable name="row2"
select="($prev and $navig.showtitles != 0)
or (generate-id($home) != generate-id(.)
or $nav.context = 'toc')
or ($chunk.tocs.and.lots != 0
and $nav.context != 'toc')
or ($next and $navig.showtitles != 0)"/>
<xsl:if test="$suppress.navigation = '0' and $suppress.footer.navigation = '0'">
<div class="navfooter">
<xsl:if test="$footer.rule != 0">
<hr/>
</xsl:if>
<xsl:if test="$row1 or $row2">
<table width="100%" summary="Navigation footer">
<xsl:if test="$row1">
<tr>
<td width="40%" align="left">
<xsl:if test="count($prev)>0">
<a accesskey="p">
<xsl:attribute name="href">
<xsl:call-template name="href.target">
<xsl:with-param name="object" select="$prev"/>
or ($next and $navig.showtitles != 0)" />
<xsl:if
test="$suppress.navigation = '0' and $suppress.footer.navigation = '0'">
<div class="navfooter">
<xsl:if test="$footer.rule != 0">
<hr />
</xsl:if>
<xsl:if test="$row1 or $row2">
<table width="100%" summary="Navigation footer">
<xsl:if test="$row1">
<tr>
<td width="40%" align="left">
<xsl:if test="count($prev)>0">
<a accesskey="p">
<xsl:attribute name="href">
<xsl:call-template
name="href.target">
<xsl:with-param
name="object" select="$prev" />
</xsl:call-template>
</xsl:attribute>
<xsl:call-template name="navig.content">
<xsl:with-param name="direction" select="'prev'"/>
</xsl:call-template>
</a>
</xsl:if>
<xsl:text>&#160;</xsl:text>
</td>
<xsl:call-template name="navig.content">
<xsl:with-param name="direction" select="'prev'" />
</xsl:call-template>
</a>
</xsl:if>
<xsl:text>&#160;</xsl:text>
</td>
<td width="20%" align="center">
<xsl:choose>
<xsl:when test="$home != . or $nav.context = 'toc'">
<a accesskey="h">
<xsl:attribute name="href">
<xsl:call-template name="href.target">
<xsl:with-param name="object" select="$home"/>
<td width="20%" align="center">
<xsl:choose>
<xsl:when test="$home != . or $nav.context = 'toc'">
<a accesskey="h">
<xsl:attribute name="href">
<xsl:call-template
name="href.target">
<xsl:with-param
name="object" select="$home" />
</xsl:call-template>
</xsl:attribute>
<xsl:call-template name="navig.content">
<xsl:with-param name="direction" select="'home'"/>
</xsl:call-template>
</a>
<xsl:if test="$chunk.tocs.and.lots != 0 and $nav.context != 'toc'">
<xsl:text>&#160;|&#160;</xsl:text>
</xsl:if>
</xsl:when>
<xsl:otherwise>&#160;</xsl:otherwise>
</xsl:choose>
<xsl:if test="$chunk.tocs.and.lots != 0 and $nav.context != 'toc'">
<a accesskey="t">
<xsl:attribute name="href">
<xsl:apply-templates select="/*[1]" mode="recursive-chunk-filename">
<xsl:with-param name="recursive" select="true()"/>
<xsl:call-template name="navig.content">
<xsl:with-param name="direction" select="'home'" />
</xsl:call-template>
</a>
<xsl:if test="$chunk.tocs.and.lots != 0 and $nav.context != 'toc'">
<xsl:text>&#160;|&#160;</xsl:text>
</xsl:if>
</xsl:when>
<xsl:otherwise>
&#160;
</xsl:otherwise>
</xsl:choose>
<xsl:if test="$chunk.tocs.and.lots != 0 and $nav.context != 'toc'">
<a accesskey="t">
<xsl:attribute name="href">
<xsl:apply-templates
select="/*[1]" mode="recursive-chunk-filename">
<xsl:with-param
name="recursive" select="true()" />
</xsl:apply-templates>
<xsl:text>-toc</xsl:text>
<xsl:value-of select="$html.ext"/>
<xsl:value-of
select="$html.ext" />
</xsl:attribute>
<xsl:call-template name="gentext">
<xsl:with-param name="key" select="'nav-toc'"/>
</xsl:call-template>
</a>
</xsl:if>
</td>
<td width="40%" align="right">
<xsl:text>&#160;</xsl:text>
<xsl:if test="count($next)>0">
<a accesskey="n">
<xsl:attribute name="href">
<xsl:call-template name="href.target">
<xsl:with-param name="object" select="$next"/>
<xsl:call-template name="gentext">
<xsl:with-param name="key" select="'nav-toc'" />
</xsl:call-template>
</a>
</xsl:if>
</td>
<td width="40%" align="right">
<xsl:text>&#160;</xsl:text>
<xsl:if test="count($next)>0">
<a accesskey="n">
<xsl:attribute name="href">
<xsl:call-template
name="href.target">
<xsl:with-param
name="object" select="$next" />
</xsl:call-template>
</xsl:attribute>
<xsl:call-template name="navig.content">
<xsl:with-param name="direction" select="'next'"/>
</xsl:call-template>
</a>
</xsl:if>
</td>
</tr>
</xsl:if>
<xsl:if test="$row2">
<tr>
<td width="40%" align="left" valign="top">
<xsl:if test="$navig.showtitles != 0">
<xsl:apply-templates select="$prev" mode="object.title.markup"/>
</xsl:if>
<xsl:text>&#160;</xsl:text>
</td>
<td width="20%" align="center">
<span style="color:white;font-size:90%;">
<a href="http://www.SpringSource.com/"
title="SpringSource - Spring from the Source">Sponsored by SpringSource
</a>
</span>
</td>
<td width="40%" align="right" valign="top">
<xsl:text>&#160;</xsl:text>
<xsl:if test="$navig.showtitles != 0">
<xsl:apply-templates select="$next" mode="object.title.markup"/>
</xsl:if>
</td>
</tr>
</xsl:if>
</table>
</xsl:if>
</div>
</xsl:if>
</xsl:template>
<xsl:call-template name="navig.content">
<xsl:with-param name="direction" select="'next'" />
</xsl:call-template>
</a>
</xsl:if>
</td>
</tr>
</xsl:if>
<xsl:if test="$row2">
<tr>
<td width="40%" align="left" valign="top">
<xsl:if test="$navig.showtitles != 0">
<xsl:apply-templates select="$prev"
mode="object.title.markup" />
</xsl:if>
<xsl:text>&#160;</xsl:text>
</td>
<td width="20%" align="center">
<span style="color:white;font-size:90%;">
<a href="http://www.SpringSource.com/" title="SpringSource - Spring from the Source">Sponsored by
SpringSource
</a>
</span>
</td>
<td width="40%" align="right" valign="top">
<xsl:text>&#160;</xsl:text>
<xsl:if test="$navig.showtitles != 0">
<xsl:apply-templates select="$next"
mode="object.title.markup" />
</xsl:if>
</td>
</tr>
</xsl:if>
</table>
</xsl:if>
</div>
</xsl:if>
</xsl:template>
</xsl:stylesheet>

View File

@ -1,11 +1,9 @@
<?xml version="1.0" encoding="UTF-8"?>
<assembly>
<!-- distribution assembly descriptor. packages up jars, source jars, documentation,
dependencies and other resources into a single archive suitable for download and
standalone use.
see pom.xml 'maven-assembly-plugin' declaration
see src/main/scripts/build-distribution.sh
see http://www.sonatype.com/books/mvnref-book/reference/assemblies-set-dist-assemblies.html -->
dependencies and other resources into a single archive suitable for download
and standalone use. see pom.xml 'maven-assembly-plugin' declaration see src/main/scripts/build-distribution.sh
see http://www.sonatype.com/books/mvnref-book/reference/assemblies-set-dist-assemblies.html -->
<id>distribution</id>
<formats>
<format>zip</format>
@ -20,19 +18,18 @@
<include>notice.txt</include>
<include>changelog.txt</include>
</includes>
<outputDirectory/>
<outputDirectory />
<lineEnding>dos</lineEnding>
</fileSet>
<fileSet>
<!-- adds reference manual (html and pdf) to the distribution archive under the
'docs/reference' directory
see pom.xml 'maven-javadoc-plugin' declaration -->
<!-- adds reference manual (html and pdf) to the distribution archive
under the 'docs/reference' directory see pom.xml 'maven-javadoc-plugin' declaration -->
<directory>target/site/reference</directory>
<outputDirectory>docs/reference</outputDirectory>
</fileSet>
<fileSet>
<!-- adds javadoc html to the distribution archive under the 'docs/javadoc' directory
see pom.xml 'maven-javadoc-plugin' declaration -->
<!-- adds javadoc html to the distribution archive under the 'docs/javadoc'
directory see pom.xml 'maven-javadoc-plugin' declaration -->
<directory>target/site/apidocs</directory>
<outputDirectory>docs/javadoc</outputDirectory>
</fileSet>

View File

@ -1,18 +1,19 @@
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>all</id>
<formats>
<format>jar</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<dependencySets>
<dependencySet>
<outputDirectory>/</outputDirectory>
<useProjectArtifact>true</useProjectArtifact>
<unpack>true</unpack>
<scope>runtime</scope>
<useTransitiveFiltering>true</useTransitiveFiltering>
</dependencySet>
</dependencySets>
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
<id>all</id>
<formats>
<format>jar</format>
</formats>
<includeBaseDirectory>false</includeBaseDirectory>
<dependencySets>
<dependencySet>
<outputDirectory>/</outputDirectory>
<useProjectArtifact>true</useProjectArtifact>
<unpack>true</unpack>
<scope>runtime</scope>
<useTransitiveFiltering>true</useTransitiveFiltering>
</dependencySet>
</dependencySets>
</assembly>

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch;
import java.util.Map;
/**
@ -24,29 +23,29 @@ import java.util.Map;
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class ElasticsearchException extends RuntimeException{
public class ElasticsearchException extends RuntimeException {
private Map<String, String> failedDocuments;
private Map<String, String> failedDocuments;
public ElasticsearchException(String message) {
super(message);
}
public ElasticsearchException(String message) {
super(message);
}
public ElasticsearchException(String message, Throwable cause) {
super(message, cause);
}
public ElasticsearchException(String message, Throwable cause) {
super(message, cause);
}
public ElasticsearchException(String message, Throwable cause, Map<String, String> failedDocuments) {
super(message, cause);
this.failedDocuments = failedDocuments;
}
public ElasticsearchException(String message, Throwable cause, Map<String, String> failedDocuments) {
super(message, cause);
this.failedDocuments = failedDocuments;
}
public ElasticsearchException(String message, Map<String, String> failedDocuments) {
super(message);
this.failedDocuments = failedDocuments;
}
public ElasticsearchException(String message, Map<String, String> failedDocuments) {
super(message);
this.failedDocuments = failedDocuments;
}
public Map<String, String> getFailedDocuments() {
return failedDocuments;
}
public Map<String, String> getFailedDocuments() {
return failedDocuments;
}
}

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch.annotations;
import org.springframework.data.annotation.Persistent;
import java.lang.annotation.*;
@ -33,10 +32,15 @@ import java.lang.annotation.*;
@Target({ ElementType.TYPE })
public @interface Document {
String indexName();
String type() default "";
short shards() default 1;
short replicas() default 5;
String refreshInterval() default "1s";
String indexStoreType() default "fs";
String indexName();
String type() default "";
short shards() default 1;
short replicas() default 5;
String refreshInterval() default "1s";
String indexStoreType() default "fs";
}

View File

@ -17,7 +17,6 @@ package org.springframework.data.elasticsearch.annotations;
import java.lang.annotation.*;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
@ -27,10 +26,14 @@ import java.lang.annotation.*;
@Documented
public @interface Field {
String type() default "";
String index() default "";
boolean store() default false;
String searchAnalyzer() default "";
String indexAnalyzer() default "";
String type() default "";
String index() default "";
boolean store() default false;
String searchAnalyzer() default "";
String indexAnalyzer() default "";
}

View File

@ -29,18 +29,18 @@ import java.lang.annotation.*;
@Documented
public @interface Query {
/**
* Elasticsearch query to be used when executing query. May contain placeholders eg. ?0
*
* @return
*/
String value() default "";
/**
* Elasticsearch query to be used when executing query. May contain placeholders eg. ?0
*
* @return
*/
String value() default "";
/**
* Named Query Named looked up by repository.
*
* @return
*/
String name() default "";
/**
* Named Query Named looked up by repository.
*
* @return
*/
String name() default "";
}

View File

@ -27,7 +27,7 @@ import org.springframework.beans.factory.InitializingBean;
import static org.elasticsearch.node.NodeBuilder.nodeBuilder;
/**
* NodeClientFactoryBean
* NodeClientFactoryBean
*
* @author Rizwan Idrees
* @author Mohsin Husen
@ -35,64 +35,64 @@ import static org.elasticsearch.node.NodeBuilder.nodeBuilder;
public class NodeClientFactoryBean implements FactoryBean<NodeClient>, InitializingBean, DisposableBean {
private static final Logger logger = LoggerFactory.getLogger(NodeClientFactoryBean.class);
private boolean local;
private boolean enableHttp;
private String clusterName;
private NodeClient nodeClient;
private static final Logger logger = LoggerFactory.getLogger(NodeClientFactoryBean.class);
private boolean local;
private boolean enableHttp;
private String clusterName;
private NodeClient nodeClient;
NodeClientFactoryBean() {
}
NodeClientFactoryBean() {
}
public NodeClientFactoryBean(boolean local) {
this.local = local;
}
public NodeClientFactoryBean(boolean local) {
this.local = local;
}
@Override
public NodeClient getObject() throws Exception {
return nodeClient;
}
@Override
public NodeClient getObject() throws Exception {
return nodeClient;
}
@Override
public Class<? extends Client> getObjectType() {
return NodeClient.class;
}
@Override
public Class<? extends Client> getObjectType() {
return NodeClient.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public void afterPropertiesSet() throws Exception {
ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder()
.put("http.enabled", String.valueOf(this.enableHttp));
@Override
public void afterPropertiesSet() throws Exception {
ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder().put("http.enabled",
String.valueOf(this.enableHttp));
nodeClient = (NodeClient) nodeBuilder().settings(settings)
.clusterName(this.clusterName).local(this.local).node().client();
}
nodeClient = (NodeClient) nodeBuilder().settings(settings).clusterName(this.clusterName).local(this.local).node()
.client();
}
public void setLocal(boolean local) {
this.local = local;
}
public void setLocal(boolean local) {
this.local = local;
}
public void setEnableHttp(boolean enableHttp) {
this.enableHttp = enableHttp;
}
public void setEnableHttp(boolean enableHttp) {
this.enableHttp = enableHttp;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
public void setClusterName(String clusterName) {
this.clusterName = clusterName;
}
@Override
public void destroy() throws Exception {
try {
logger.info("Closing elasticSearch client");
if (nodeClient != null) {
nodeClient.close();
}
} catch (final Exception e) {
logger.error("Error closing ElasticSearch client: ", e);
}
}
@Override
public void destroy() throws Exception {
try {
logger.info("Closing elasticSearch client");
if (nodeClient != null) {
nodeClient.close();
}
} catch (final Exception e) {
logger.error("Error closing ElasticSearch client: ", e);
}
}
}

View File

@ -32,7 +32,7 @@ import static org.apache.commons.lang.StringUtils.substringBefore;
import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilder;
/**
* TransportClientFactoryBean
* TransportClientFactoryBean
*
* @author Rizwan Idrees
* @author Mohsin Husen
@ -40,71 +40,70 @@ import static org.elasticsearch.common.settings.ImmutableSettings.settingsBuilde
public class TransportClientFactoryBean implements FactoryBean<TransportClient>, InitializingBean, DisposableBean {
private static final Logger logger = LoggerFactory.getLogger(TransportClientFactoryBean.class);
private String[] clusterNodes;
private TransportClient client;
private Properties properties;
static final String COLON = ":";
private static final Logger logger = LoggerFactory.getLogger(TransportClientFactoryBean.class);
private String[] clusterNodes;
private TransportClient client;
private Properties properties;
static final String COLON = ":";
@Override
public void destroy() throws Exception {
try {
logger.info("Closing elasticSearch client");
if (client != null) {
client.close();
}
} catch (final Exception e) {
logger.error("Error closing ElasticSearch client: ", e);
}
}
@Override
public void destroy() throws Exception {
try {
logger.info("Closing elasticSearch client");
if (client != null) {
client.close();
}
} catch (final Exception e) {
logger.error("Error closing ElasticSearch client: ", e);
}
}
@Override
public TransportClient getObject() throws Exception {
return client;
}
@Override
public TransportClient getObject() throws Exception {
return client;
}
@Override
public Class<TransportClient> getObjectType() {
return TransportClient.class;
}
@Override
public Class<TransportClient> getObjectType() {
return TransportClient.class;
}
@Override
public boolean isSingleton() {
return false;
}
@Override
public boolean isSingleton() {
return false;
}
@Override
public void afterPropertiesSet() throws Exception {
buildClient();
}
@Override
public void afterPropertiesSet() throws Exception {
buildClient();
}
protected void buildClient() throws Exception {
client = new TransportClient(settings());
Assert.notEmpty(clusterNodes,"[Assertion failed] clusterNodes settings missing.");
for (String clusterNode : clusterNodes) {
String hostName = substringBefore(clusterNode, COLON);
String port = substringAfter(clusterNode, COLON);
Assert.hasText(hostName,"[Assertion failed] missing host name in 'clusterNodes'");
Assert.hasText(port,"[Assertion failed] missing port in 'clusterNodes'");
logger.info("adding transport node : " + clusterNode);
client.addTransportAddress(new InetSocketTransportAddress(hostName, Integer.valueOf(port)));
}
client.connectedNodes();
}
protected void buildClient() throws Exception {
client = new TransportClient(settings());
Assert.notEmpty(clusterNodes, "[Assertion failed] clusterNodes settings missing.");
for (String clusterNode : clusterNodes) {
String hostName = substringBefore(clusterNode, COLON);
String port = substringAfter(clusterNode, COLON);
Assert.hasText(hostName, "[Assertion failed] missing host name in 'clusterNodes'");
Assert.hasText(port, "[Assertion failed] missing port in 'clusterNodes'");
logger.info("adding transport node : " + clusterNode);
client.addTransportAddress(new InetSocketTransportAddress(hostName, Integer.valueOf(port)));
}
client.connectedNodes();
}
private Settings settings(){
if(properties != null){
return settingsBuilder().put(properties).build();
}
return settingsBuilder()
.put("client.transport.sniff",true).build();
}
private Settings settings() {
if (properties != null) {
return settingsBuilder().put(properties).build();
}
return settingsBuilder().put("client.transport.sniff", true).build();
}
public void setClusterNodes(String[] clusterNodes) {
this.clusterNodes = clusterNodes;
}
public void setClusterNodes(String[] clusterNodes) {
this.clusterNodes = clusterNodes;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
public void setProperties(Properties properties) {
this.properties = properties;
}
}

View File

@ -21,21 +21,21 @@ import org.springframework.data.repository.config.RepositoryBeanDefinitionParser
import org.springframework.data.repository.config.RepositoryConfigurationExtension;
/**
* ElasticsearchNamespaceHandler
* ElasticsearchNamespaceHandler
*
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class ElasticsearchNamespaceHandler extends NamespaceHandlerSupport{
public class ElasticsearchNamespaceHandler extends NamespaceHandlerSupport {
@Override
public void init() {
RepositoryConfigurationExtension extension = new ElasticsearchRepositoryConfigExtension();
@Override
public void init() {
RepositoryConfigurationExtension extension = new ElasticsearchRepositoryConfigExtension();
RepositoryBeanDefinitionParser parser = new RepositoryBeanDefinitionParser(extension);
registerBeanDefinitionParser("repositories", parser);
registerBeanDefinitionParser("node-client", new NodeClientBeanDefinitionParser());
registerBeanDefinitionParser("transport-client", new TransportClientBeanDefinitionParser());
}
}
}

View File

@ -32,24 +32,23 @@ import org.w3c.dom.Element;
public class NodeClientBeanDefinitionParser extends AbstractBeanDefinitionParser {
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(NodeClientFactoryBean.class);
setLocalSettings(element,builder);
return getSourcedBeanDefinition(builder, element, parserContext);
}
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(NodeClientFactoryBean.class);
setLocalSettings(element, builder);
return getSourcedBeanDefinition(builder, element, parserContext);
}
private void setLocalSettings(Element element, BeanDefinitionBuilder builder) {
builder.addPropertyValue("local", Boolean.valueOf(element.getAttribute("local")));
builder.addPropertyValue("clusterName", element.getAttribute("cluster-name"));
builder.addPropertyValue("enableHttp",Boolean.valueOf(element.getAttribute("http-enabled")));
}
private void setLocalSettings(Element element, BeanDefinitionBuilder builder) {
builder.addPropertyValue("local", Boolean.valueOf(element.getAttribute("local")));
builder.addPropertyValue("clusterName", element.getAttribute("cluster-name"));
builder.addPropertyValue("enableHttp", Boolean.valueOf(element.getAttribute("http-enabled")));
}
private AbstractBeanDefinition getSourcedBeanDefinition(BeanDefinitionBuilder builder, Element source,
ParserContext context) {
AbstractBeanDefinition definition = builder.getBeanDefinition();
definition.setSource(context.extractSource(source));
return definition;
}
private AbstractBeanDefinition getSourcedBeanDefinition(BeanDefinitionBuilder builder, Element source,
ParserContext context) {
AbstractBeanDefinition definition = builder.getBeanDefinition();
definition.setSource(context.extractSource(source));
return definition;
}
}

View File

@ -23,8 +23,9 @@ import org.springframework.data.elasticsearch.client.TransportClientFactoryBean;
import org.w3c.dom.Element;
import static org.apache.commons.lang.StringUtils.split;
/**
* TransportClientBeanDefinitionParser
* TransportClientBeanDefinitionParser
*
* @author Rizwan Idrees
* @author Mohsin Husen
@ -32,23 +33,23 @@ import static org.apache.commons.lang.StringUtils.split;
public class TransportClientBeanDefinitionParser extends AbstractBeanDefinitionParser {
private static final String SEPARATOR_CHARS = ",";
private static final String SEPARATOR_CHARS = ",";
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TransportClientFactoryBean.class);
setClusterNodes(element, builder);
return getSourcedBeanDefinition(builder,element, parserContext);
}
@Override
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TransportClientFactoryBean.class);
setClusterNodes(element, builder);
return getSourcedBeanDefinition(builder, element, parserContext);
}
private void setClusterNodes(Element element, BeanDefinitionBuilder builder){
builder.addPropertyValue("clusterNodes", split(element.getAttribute("cluster-nodes"), SEPARATOR_CHARS));
}
private void setClusterNodes(Element element, BeanDefinitionBuilder builder) {
builder.addPropertyValue("clusterNodes", split(element.getAttribute("cluster-nodes"), SEPARATOR_CHARS));
}
private AbstractBeanDefinition getSourcedBeanDefinition(BeanDefinitionBuilder builder, Element source,
ParserContext context) {
AbstractBeanDefinition definition = builder.getBeanDefinition();
definition.setSource(context.extractSource(source));
return definition;
}
private AbstractBeanDefinition getSourcedBeanDefinition(BeanDefinitionBuilder builder, Element source,
ParserContext context) {
AbstractBeanDefinition definition = builder.getBeanDefinition();
definition.setSource(context.extractSource(source));
return definition;
}
}

View File

@ -35,100 +35,103 @@ import static org.springframework.data.elasticsearch.core.query.Criteria.Operati
*/
class CriteriaQueryProcessor {
QueryBuilder createQueryFromCriteria(Criteria criteria) {
BoolQueryBuilder query = boolQuery();
QueryBuilder createQueryFromCriteria(Criteria criteria) {
BoolQueryBuilder query = boolQuery();
ListIterator<Criteria> chainIterator = criteria.getCriteriaChain().listIterator();
while (chainIterator.hasNext()) {
Criteria chainedCriteria = chainIterator.next();
if (chainedCriteria.isOr()) {
query.should(createQueryFragmentForCriteria(chainedCriteria));
} else if (chainedCriteria.isNegating()) {
query.mustNot(createQueryFragmentForCriteria(chainedCriteria));
} else {
query.must(createQueryFragmentForCriteria(chainedCriteria));
}
}
return query;
}
ListIterator<Criteria> chainIterator = criteria.getCriteriaChain().listIterator();
while (chainIterator.hasNext()) {
Criteria chainedCriteria = chainIterator.next();
if(chainedCriteria.isOr()){
query.should(createQueryFragmentForCriteria(chainedCriteria));
}else if(chainedCriteria.isNegating()){
query.mustNot(createQueryFragmentForCriteria(chainedCriteria));
}else{
query.must(createQueryFragmentForCriteria(chainedCriteria));
}
}
return query;
}
private QueryBuilder createQueryFragmentForCriteria(Criteria chainedCriteria) {
Iterator<Criteria.CriteriaEntry> it = chainedCriteria.getCriteriaEntries().iterator();
boolean singeEntryCriteria = (chainedCriteria.getCriteriaEntries().size() == 1);
String fieldName = chainedCriteria.getField().getName();
Assert.notNull(fieldName, "Unknown field");
QueryBuilder query = null;
private QueryBuilder createQueryFragmentForCriteria(Criteria chainedCriteria) {
Iterator<Criteria.CriteriaEntry> it = chainedCriteria.getCriteriaEntries().iterator();
boolean singeEntryCriteria = (chainedCriteria.getCriteriaEntries().size() == 1);
if (singeEntryCriteria) {
Criteria.CriteriaEntry entry = it.next();
query = processCriteriaEntry(entry.getKey(), entry.getValue(), fieldName);
} else {
query = boolQuery();
while (it.hasNext()) {
Criteria.CriteriaEntry entry = it.next();
((BoolQueryBuilder) query).must(processCriteriaEntry(entry.getKey(), entry.getValue(), fieldName));
}
}
String fieldName = chainedCriteria.getField().getName();
Assert.notNull(fieldName,"Unknown field");
QueryBuilder query = null;
addBoost(query, chainedCriteria.getBoost());
return query;
}
if(singeEntryCriteria){
Criteria.CriteriaEntry entry = it.next();
query = processCriteriaEntry(entry.getKey(), entry.getValue(), fieldName);
}else{
query = boolQuery();
while (it.hasNext()){
Criteria.CriteriaEntry entry = it.next();
((BoolQueryBuilder)query).must(processCriteriaEntry(entry.getKey(), entry.getValue(), fieldName));
}
}
private QueryBuilder processCriteriaEntry(OperationKey key, Object value, String fieldName) {
if (value == null) {
return null;
}
QueryBuilder query = null;
addBoost(query, chainedCriteria.getBoost());
return query;
}
switch (key) {
case EQUALS:
query = fieldQuery(fieldName, value);
break;
case CONTAINS:
query = fieldQuery(fieldName, "*" + value + "*").analyzeWildcard(true);
break;
case STARTS_WITH:
query = fieldQuery(fieldName, value + "*").analyzeWildcard(true);
break;
case ENDS_WITH:
query = fieldQuery(fieldName, "*" + value).analyzeWildcard(true);
break;
case EXPRESSION:
query = queryString((String) value).field(fieldName);
break;
case BETWEEN:
Object[] ranges = (Object[]) value;
query = rangeQuery(fieldName).from(ranges[0]).to(ranges[1]);
break;
case FUZZY:
query = fuzzyQuery(fieldName, (String) value);
break;
case IN:
query = boolQuery();
Iterable<Object> collection = (Iterable<Object>) value;
for (Object item : collection) {
((BoolQueryBuilder) query).should(fieldQuery(fieldName, item));
}
break;
}
return query;
}
private QueryBuilder processCriteriaEntry(OperationKey key, Object value, String fieldName) {
if (value == null) {
return null;
}
QueryBuilder query = null;
private QueryBuilder buildNegationQuery(String fieldName, Iterator<Criteria.CriteriaEntry> it) {
BoolQueryBuilder notQuery = boolQuery();
while (it.hasNext()) {
notQuery.mustNot(fieldQuery(fieldName, it.next().getValue()));
}
return notQuery;
}
switch (key){
case EQUALS:
query = fieldQuery(fieldName, value); break;
case CONTAINS:
query = fieldQuery(fieldName,"*" + value + "*").analyzeWildcard(true); break;
case STARTS_WITH:
query = fieldQuery(fieldName,value +"*").analyzeWildcard(true); break;
case ENDS_WITH:
query = fieldQuery(fieldName, "*"+value).analyzeWildcard(true); break;
case EXPRESSION:
query = queryString((String)value).field(fieldName); break;
case BETWEEN:
Object[] ranges = (Object[]) value;
query = rangeQuery(fieldName).from(ranges[0]).to(ranges[1]); break;
case FUZZY:
query = fuzzyQuery(fieldName, (String) value); break;
case IN:
query = boolQuery();
Iterable<Object> collection = (Iterable<Object>) value;
for(Object item : collection){
((BoolQueryBuilder) query).should(fieldQuery(fieldName, item));
}
break;
}
return query;
}
private QueryBuilder buildNegationQuery(String fieldName, Iterator<Criteria.CriteriaEntry> it){
BoolQueryBuilder notQuery = boolQuery();
while (it.hasNext()){
notQuery.mustNot(fieldQuery(fieldName, it.next().getValue()));
}
return notQuery;
}
private void addBoost(QueryBuilder query, float boost){
if(Float.isNaN(boost)){
return;
}
if(query instanceof BoostableQueryBuilder){
((BoostableQueryBuilder)query).boost(boost);
}
}
private void addBoost(QueryBuilder query, float boost) {
if (Float.isNaN(boost)) {
return;
}
if (query instanceof BoostableQueryBuilder) {
((BoostableQueryBuilder) query).boost(boost);
}
}
}

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch.core;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.core.query.*;
@ -30,229 +29,232 @@ import java.util.List;
*/
public interface ElasticsearchOperations {
/**
* @return Converter in use
*/
ElasticsearchConverter getElasticsearchConverter();
/**
* @return Converter in use
*/
ElasticsearchConverter getElasticsearchConverter();
/**
* Create an index for a class
*
* @param clazz
* @param <T>
*/
<T> boolean createIndex(Class<T> clazz);
/**
* Create an index for a class
* @param clazz
* @param <T>
*/
<T> boolean createIndex(Class<T> clazz);
/**
* Create mapping for a class
*
* @param clazz
* @param <T>
*/
<T> boolean putMapping(Class<T> clazz);
/**
* Create mapping for a class
* @param clazz
* @param <T>
*/
<T> boolean putMapping(Class<T> clazz);
/**
* Execute the query against elasticsearch and return the first returned object
*
* @param query
* @param clazz
* @return the first matching object
*/
<T> T queryForObject(GetQuery query, Class<T> clazz);
/**
* Execute the query against elasticsearch and return the first returned object
*
* @param query
* @param clazz
* @return the first matching object
*/
<T> T queryForObject(CriteriaQuery query, Class<T> clazz);
/**
* Execute the query against elasticsearch and return the first returned object
*
* @param query
* @param clazz
* @return the first matching object
*/
<T> T queryForObject(GetQuery query, Class<T> clazz);
/**
* Execute the query against elasticsearch and return the first returned object
*
* @param query
* @param clazz
* @return the first matching object
*/
<T> T queryForObject(StringQuery query, Class<T> clazz);
/**
* Execute the query against elasticsearch and return the first returned object
*
* @param query
* @param clazz
* @return the first matching object
*/
<T> T queryForObject(CriteriaQuery query, Class<T> clazz);
/**
* Execute the query against elasticsearch and return result as {@link Page}
*
* @param query
* @param clazz
* @return
*/
<T> Page<T> queryForPage(SearchQuery query, Class<T> clazz);
/**
* Execute the query against elasticsearch and return result as {@link Page}
*
* @param query
* @param resultsMapper
* @return
*/
<T> Page<T> queryForPage(SearchQuery query, ResultsMapper<T> resultsMapper);
/**
* Execute the query against elasticsearch and return the first returned object
*
* @param query
* @param clazz
* @return the first matching object
*/
<T> T queryForObject(StringQuery query, Class<T> clazz);
/**
* Execute the query against elasticsearch and return result as {@link Page}
*
* @param query
* @param clazz
* @return
*/
<T> Page<T> queryForPage(CriteriaQuery query, Class<T> clazz);
/**
* Execute the query against elasticsearch and return result as {@link Page}
*
* @param query
* @param clazz
* @return
*/
<T> Page<T> queryForPage(StringQuery query, Class<T> clazz);
/**
* Execute the query against elasticsearch and return result as {@link Page}
*
* @param query
* @param clazz
* @return
*/
<T> Page<T> queryForPage(SearchQuery query, Class<T> clazz);
/**
* Execute the criteria query against elasticsearch and return result as {@link List}
*
* @param query
* @param clazz
* @param <T>
* @return
*/
<T> List<T> queryForList(CriteriaQuery query, Class<T> clazz);
/**
* Execute the string query against elasticsearch and return result as {@link List}
*
* @param query
* @param clazz
* @param <T>
* @return
*/
<T> List<T> queryForList(StringQuery query, Class<T> clazz);
/**
* Execute the query against elasticsearch and return result as {@link Page}
*
* @param query
* @param resultsMapper
* @return
*/
<T> Page<T> queryForPage(SearchQuery query, ResultsMapper<T> resultsMapper);
/**
* Execute the query against elasticsearch and return ids
*
* @param query
* @return
*/
<T> List<String> queryForIds(SearchQuery query);
/**
* return number of elements found by for given query
*
* @param query
* @param clazz
* @return
*/
<T> long count(SearchQuery query, Class<T> clazz);
/**
* Execute the query against elasticsearch and return result as {@link Page}
*
* @param query
* @param clazz
* @return
*/
<T> Page<T> queryForPage(CriteriaQuery query, Class<T> clazz);
/**
* Index an object. Will do save or update
*
* @param query
* @return returns the document id
*/
String index(IndexQuery query);
/**
* Bulk index all objects. Will do save or update
*
* @param queries
*/
void bulkIndex(List<IndexQuery> queries);
/**
* Execute the query against elasticsearch and return result as {@link Page}
*
* @param query
* @param clazz
* @return
*/
<T> Page<T> queryForPage(StringQuery query, Class<T> clazz);
/**
* Delete the one object with provided id
*
* @param indexName
* @param type
* @param id
* @return documentId of the document deleted
*/
String delete(String indexName, String type, String id);
/**
* Execute the criteria query against elasticsearch and return result as {@link List}
*
* @param query
* @param clazz
* @param <T>
* @return
*/
<T> List<T> queryForList(CriteriaQuery query, Class<T> clazz);
/**
* Delete the one object with provided id
*
* @param clazz
* @param id
* @return documentId of the document deleted
*/
<T> String delete(Class<T> clazz, String id);
/**
* Execute the string query against elasticsearch and return result as {@link List}
*
* @param query
* @param clazz
* @param <T>
* @return
*/
<T> List<T> queryForList(StringQuery query, Class<T> clazz);
/**
* Delete all records matching the query
*
* @param clazz
* @param query
*/
<T> void delete(DeleteQuery query, Class<T> clazz);
/**
* Execute the query against elasticsearch and return ids
*
* @param query
* @return
*/
<T> List<String> queryForIds(SearchQuery query);
/**
* Deletes an index for given entity
*
* @param clazz
* @param <T>
* @return
*/
<T> boolean deleteIndex(Class<T> clazz);
/**
* return number of elements found by for given query
*
* @param query
* @param clazz
* @return
*/
<T> long count(SearchQuery query, Class<T> clazz);
/**
* check if index is exists
*
* @param clazz
* @param <T>
* @return
*/
<T> boolean indexExists(Class<T> clazz);
/**
* Index an object. Will do save or update
*
* @param query
* @return returns the document id
*/
String index(IndexQuery query);
/**
* refresh the index
*
* @param indexName
* @param waitForOperation
*/
void refresh(String indexName, boolean waitForOperation);
/**
* Bulk index all objects. Will do save or update
*
* @param queries
*/
void bulkIndex(List<IndexQuery> queries);
/**
* refresh the index
*
* @param clazz
* @param waitForOperation
*/
<T> void refresh(Class<T> clazz, boolean waitForOperation);
/**
* Delete the one object with provided id
*
* @param indexName
* @param type
* @param id
* @return documentId of the document deleted
*/
String delete(String indexName, String type, String id);
/**
* Returns scroll id for scan query
*
* @param query
* @param scrollTimeInMillis
* @param noFields
* @return
*/
String scan(SearchQuery query, long scrollTimeInMillis, boolean noFields);
/**
* Delete the one object with provided id
*
* @param clazz
* @param id
* @return documentId of the document deleted
*/
<T> String delete(Class<T> clazz, String id);
/**
* Scrolls the results for give scroll id
*
* @param scrollId
* @param scrollTimeInMillis
* @param resultsMapper
* @param <T>
* @return
*/
<T> Page<T> scroll(String scrollId, long scrollTimeInMillis, ResultsMapper<T> resultsMapper);
/**
* Delete all records matching the query
* @param clazz
* @param query
*/
<T> void delete(DeleteQuery query, Class<T> clazz);
/**
* Deletes an index for given entity
* @param clazz
* @param <T>
* @return
*/
<T> boolean deleteIndex(Class<T> clazz);
/**
* check if index is exists
* @param clazz
* @param <T>
* @return
*/
<T> boolean indexExists(Class<T> clazz);
/**
* refresh the index
* @param indexName
* @param waitForOperation
*/
void refresh(String indexName,boolean waitForOperation);
/**
* refresh the index
* @param clazz
* @param waitForOperation
*/
<T> void refresh(Class<T> clazz,boolean waitForOperation);
/**
* Returns scroll id for scan query
* @param query
* @param scrollTimeInMillis
* @param noFields
* @return
*/
String scan(SearchQuery query, long scrollTimeInMillis, boolean noFields);
/**
* Scrolls the results for give scroll id
* @param scrollId
* @param scrollTimeInMillis
* @param resultsMapper
* @param <T>
* @return
*/
<T> Page<T> scroll(String scrollId, long scrollTimeInMillis, ResultsMapper<T> resultsMapper);
/**
* more like this query to search for documents that are "like" a specific document.
* @param query
* @param clazz
* @param <T>
* @return
*/
<T> Page<T> moreLikeThis(MoreLikeThisQuery query, Class<T> clazz);
/**
* more like this query to search for documents that are "like" a specific document.
*
* @param query
* @param clazz
* @param <T>
* @return
*/
<T> Page<T> moreLikeThis(MoreLikeThisQuery query, Class<T> clazz);
}

View File

@ -76,450 +76,436 @@ import static org.springframework.data.elasticsearch.core.MappingBuilder.buildMa
public class ElasticsearchTemplate implements ElasticsearchOperations {
private Client client;
private ElasticsearchConverter elasticsearchConverter;
private ObjectMapper objectMapper = new ObjectMapper();
private Client client;
private ElasticsearchConverter elasticsearchConverter;
private ObjectMapper objectMapper = new ObjectMapper();
{
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
{
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
}
public ElasticsearchTemplate(Client client) {
this(client, null);
}
public ElasticsearchTemplate(Client client) {
this(client, null);
}
public ElasticsearchTemplate(Client client, ElasticsearchConverter elasticsearchConverter) {
this.client = client;
this.elasticsearchConverter = (elasticsearchConverter == null)? new MappingElasticsearchConverter(new SimpleElasticsearchMappingContext()) : elasticsearchConverter ;
}
public ElasticsearchTemplate(Client client, ElasticsearchConverter elasticsearchConverter) {
this.client = client;
this.elasticsearchConverter = (elasticsearchConverter == null) ? new MappingElasticsearchConverter(
new SimpleElasticsearchMappingContext()) : elasticsearchConverter;
}
@Override
public <T> boolean createIndex(Class<T> clazz) {
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
return createIndexIfNotCreated(clazz);
}
@Override
public <T> boolean createIndex(Class<T> clazz) {
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
return createIndexIfNotCreated(clazz);
}
@Override
public <T> boolean putMapping(Class<T> clazz) {
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
PutMappingRequestBuilder requestBuilder = client.admin().indices().preparePutMapping(persistentEntity.getIndexName())
.setType(persistentEntity.getIndexType());
@Override
public <T> boolean putMapping(Class<T> clazz) {
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
PutMappingRequestBuilder requestBuilder = client.admin().indices()
.preparePutMapping(persistentEntity.getIndexName()).setType(persistentEntity.getIndexType());
try {
XContentBuilder xContentBuilder = buildMapping(clazz, persistentEntity.getIndexType(), persistentEntity.getIdProperty().getFieldName());
return requestBuilder.setSource(xContentBuilder).execute().actionGet().isAcknowledged();
} catch (Exception e) {
throw new ElasticsearchException("Failed to build mapping for " + clazz.getSimpleName() , e);
}
}
try {
XContentBuilder xContentBuilder = buildMapping(clazz, persistentEntity.getIndexType(), persistentEntity
.getIdProperty().getFieldName());
return requestBuilder.setSource(xContentBuilder).execute().actionGet().isAcknowledged();
} catch (Exception e) {
throw new ElasticsearchException("Failed to build mapping for " + clazz.getSimpleName(), e);
}
}
@Override
public ElasticsearchConverter getElasticsearchConverter() {
return elasticsearchConverter;
}
@Override
public ElasticsearchConverter getElasticsearchConverter() {
return elasticsearchConverter;
}
@Override
public <T> T queryForObject(GetQuery query, Class<T> clazz) {
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
GetResponse response = client.prepareGet(persistentEntity.getIndexName(), persistentEntity.getIndexType(), query.getId())
.execute().actionGet();
return mapResult(response.getSourceAsString(), clazz);
}
@Override
public <T> T queryForObject(GetQuery query, Class<T> clazz) {
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
GetResponse response = client
.prepareGet(persistentEntity.getIndexName(), persistentEntity.getIndexType(), query.getId()).execute()
.actionGet();
return mapResult(response.getSourceAsString(), clazz);
}
@Override
public <T> T queryForObject(CriteriaQuery query, Class<T> clazz) {
Page<T> page = queryForPage(query,clazz);
Assert.isTrue(page.getTotalElements() < 2, "Expected 1 but found "+ page.getTotalElements() +" results");
return page.getTotalElements() > 0? page.getContent().get(0) : null;
}
@Override
public <T> T queryForObject(CriteriaQuery query, Class<T> clazz) {
Page<T> page = queryForPage(query, clazz);
Assert.isTrue(page.getTotalElements() < 2, "Expected 1 but found " + page.getTotalElements() + " results");
return page.getTotalElements() > 0 ? page.getContent().get(0) : null;
}
@Override
public <T> T queryForObject(StringQuery query, Class<T> clazz) {
Page<T> page = queryForPage(query,clazz);
Assert.isTrue(page.getTotalElements() < 2, "Expected 1 but found "+ page.getTotalElements() +" results");
return page.getTotalElements() > 0? page.getContent().get(0) : null;
}
@Override
public <T> T queryForObject(StringQuery query, Class<T> clazz) {
Page<T> page = queryForPage(query, clazz);
Assert.isTrue(page.getTotalElements() < 2, "Expected 1 but found " + page.getTotalElements() + " results");
return page.getTotalElements() > 0 ? page.getContent().get(0) : null;
}
@Override
public <T> Page<T> queryForPage(SearchQuery query, Class<T> clazz) {
SearchResponse response = doSearch(prepareSearch(query,clazz), query.getQuery(), query.getFilter(), query.getElasticsearchSort());
return mapResults(response, clazz, query.getPageable());
}
@Override
public <T> Page<T> queryForPage(SearchQuery query, Class<T> clazz) {
SearchResponse response = doSearch(prepareSearch(query, clazz), query.getQuery(), query.getFilter(),
query.getElasticsearchSort());
return mapResults(response, clazz, query.getPageable());
}
@Override
public <T> Page<T> queryForPage(SearchQuery query, ResultsMapper<T> resultsMapper) {
SearchResponse response = doSearch(prepareSearch(query), query.getQuery(), query.getFilter(), query.getElasticsearchSort());
return resultsMapper.mapResults(response);
}
@Override
public <T> Page<T> queryForPage(SearchQuery query, ResultsMapper<T> resultsMapper) {
SearchResponse response = doSearch(prepareSearch(query), query.getQuery(), query.getFilter(),
query.getElasticsearchSort());
return resultsMapper.mapResults(response);
}
@Override
public <T> List<T> queryForList(CriteriaQuery query, Class<T> clazz){
return queryForPage(query, clazz).getContent();
}
@Override
public <T> List<T> queryForList(CriteriaQuery query, Class<T> clazz) {
return queryForPage(query, clazz).getContent();
}
@Override
public <T> List<T> queryForList(StringQuery query, Class<T> clazz){
return queryForPage(query, clazz).getContent();
}
@Override
public <T> List<T> queryForList(StringQuery query, Class<T> clazz) {
return queryForPage(query, clazz).getContent();
}
@Override
public <T> List<String> queryForIds(SearchQuery query) {
SearchRequestBuilder request = prepareSearch(query).setQuery(query.getQuery()).setNoFields();
if (query.getFilter() != null) {
request.setFilter(query.getFilter());
}
SearchResponse response = request.execute().actionGet();
return extractIds(response);
}
@Override
public <T> List<String> queryForIds(SearchQuery query) {
SearchRequestBuilder request = prepareSearch(query).setQuery(query.getQuery())
.setNoFields();
if(query.getFilter() != null){
request.setFilter(query.getFilter());
}
SearchResponse response = request.execute().actionGet();
return extractIds(response);
}
@Override
public <T> Page<T> queryForPage(CriteriaQuery criteriaQuery, Class<T> clazz) {
QueryBuilder query = new CriteriaQueryProcessor().createQueryFromCriteria(criteriaQuery.getCriteria());
SearchResponse response = prepareSearch(criteriaQuery, clazz).setQuery(query).execute().actionGet();
return mapResults(response, clazz, criteriaQuery.getPageable());
}
@Override
public <T> Page<T> queryForPage(CriteriaQuery criteriaQuery, Class<T> clazz) {
QueryBuilder query = new CriteriaQueryProcessor().createQueryFromCriteria(criteriaQuery.getCriteria());
SearchResponse response = prepareSearch(criteriaQuery,clazz)
.setQuery(query)
.execute().actionGet();
return mapResults(response, clazz, criteriaQuery.getPageable());
}
@Override
public <T> Page<T> queryForPage(StringQuery query, Class<T> clazz) {
SearchResponse response = prepareSearch(query, clazz).setQuery(query.getSource()).execute().actionGet();
return mapResults(response, clazz, query.getPageable());
}
@Override
public <T> Page<T> queryForPage(StringQuery query, Class<T> clazz) {
SearchResponse response = prepareSearch(query,clazz)
.setQuery(query.getSource())
.execute().actionGet();
return mapResults(response, clazz, query.getPageable());
}
@Override
public <T> long count(SearchQuery query, Class<T> clazz) {
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
CountRequestBuilder countRequestBuilder = client.prepareCount(persistentEntity.getIndexName()).setTypes(
persistentEntity.getIndexType());
if (query.getQuery() != null) {
countRequestBuilder.setQuery(query.getQuery());
}
return countRequestBuilder.execute().actionGet().getCount();
}
@Override
public <T> long count(SearchQuery query, Class<T> clazz) {
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
CountRequestBuilder countRequestBuilder = client.prepareCount(persistentEntity.getIndexName())
.setTypes(persistentEntity.getIndexType());
if(query.getQuery() != null){
countRequestBuilder.setQuery(query.getQuery());
}
return countRequestBuilder.execute().actionGet().getCount();
}
@Override
public String index(IndexQuery query) {
return prepareIndex(query).execute().actionGet().getId();
}
@Override
public String index(IndexQuery query) {
return prepareIndex(query)
.execute()
.actionGet().getId();
}
@Override
public void bulkIndex(List<IndexQuery> queries) {
BulkRequestBuilder bulkRequest = client.prepareBulk();
for (IndexQuery query : queries) {
bulkRequest.add(prepareIndex(query));
}
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
if (bulkResponse.hasFailures()) {
Map<String, String> failedDocuments = new HashMap<String, String>();
for (BulkItemResponse item : bulkResponse.getItems()) {
if (item.isFailed())
failedDocuments.put(item.getId(), item.getFailureMessage());
}
throw new ElasticsearchException(
"Bulk indexing has failures. Use ElasticsearchException.getFailedDocuments() for detailed messages ["
+ failedDocuments + "]", failedDocuments);
}
}
@Override
public void bulkIndex(List<IndexQuery> queries) {
BulkRequestBuilder bulkRequest = client.prepareBulk();
for(IndexQuery query : queries){
bulkRequest.add(prepareIndex(query));
}
BulkResponse bulkResponse = bulkRequest.execute().actionGet();
if (bulkResponse.hasFailures()) {
Map<String, String> failedDocuments = new HashMap<String, String>();
for (BulkItemResponse item : bulkResponse.getItems()) {
if (item.isFailed())
failedDocuments.put(item.getId(), item.getFailureMessage());
}
throw new ElasticsearchException("Bulk indexing has failures. Use ElasticsearchException.getFailedDocuments() for detailed messages [" + failedDocuments+"]", failedDocuments);
}
}
@Override
public <T> boolean indexExists(Class<T> clazz) {
return indexExists(getPersistentEntityFor(clazz).getIndexName());
}
@Override
public <T> boolean indexExists(Class<T> clazz){
return indexExists(getPersistentEntityFor(clazz).getIndexName());
}
@Override
public <T> boolean deleteIndex(Class<T> clazz) {
String indexName = getPersistentEntityFor(clazz).getIndexName();
if (indexExists(indexName)) {
return client.admin().indices().delete(new DeleteIndexRequest(indexName)).actionGet().isAcknowledged();
}
return false;
}
@Override
public <T> boolean deleteIndex(Class<T> clazz){
String indexName = getPersistentEntityFor(clazz).getIndexName();
if(indexExists(indexName)){
return client.admin().indices().delete(new DeleteIndexRequest(indexName)).actionGet().isAcknowledged();
}
return false;
}
@Override
public String delete(String indexName, String type, String id) {
return client.prepareDelete(indexName, type, id).execute().actionGet().getId();
}
@Override
public String delete(String indexName, String type, String id) {
return client.prepareDelete(indexName, type, id)
.execute().actionGet().getId();
}
@Override
public <T> String delete(Class<T> clazz, String id) {
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
return delete(persistentEntity.getIndexName(), persistentEntity.getIndexType(), id);
}
@Override
public <T> String delete(Class<T> clazz, String id) {
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
return delete(persistentEntity.getIndexName(), persistentEntity.getIndexType(), id);
}
@Override
public <T> void delete(DeleteQuery deleteQuery, Class<T> clazz) {
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
client.prepareDeleteByQuery(persistentEntity.getIndexName()).setTypes(persistentEntity.getIndexType())
.setQuery(deleteQuery.getQuery()).execute().actionGet();
}
@Override
public <T> void delete(DeleteQuery deleteQuery, Class<T> clazz) {
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
client.prepareDeleteByQuery(persistentEntity.getIndexName())
.setTypes(persistentEntity.getIndexType())
.setQuery(deleteQuery.getQuery())
.execute().actionGet();
}
@Override
public String scan(SearchQuery searchQuery, long scrollTimeInMillis, boolean noFields) {
Assert.notNull(searchQuery.getIndices(), "No index defined for Query");
Assert.notNull(searchQuery.getTypes(), "No type define for Query");
Assert.notNull(searchQuery.getPageable(), "Query.pageable is required for scan & scroll");
@Override
public String scan(SearchQuery searchQuery, long scrollTimeInMillis, boolean noFields) {
Assert.notNull(searchQuery.getIndices(), "No index defined for Query");
Assert.notNull(searchQuery.getTypes(), "No type define for Query");
Assert.notNull(searchQuery.getPageable(), "Query.pageable is required for scan & scroll");
SearchRequestBuilder requestBuilder = client.prepareSearch(toArray(searchQuery.getIndices())).setSearchType(SCAN)
.setQuery(searchQuery.getQuery()).setTypes(toArray(searchQuery.getTypes()))
.setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)).setFrom(0)
.setSize(searchQuery.getPageable().getPageSize());
SearchRequestBuilder requestBuilder = client.prepareSearch(toArray(searchQuery.getIndices()))
.setSearchType(SCAN)
.setQuery(searchQuery.getQuery())
.setTypes(toArray(searchQuery.getTypes()))
.setScroll(TimeValue.timeValueMillis(scrollTimeInMillis))
.setFrom(0)
.setSize(searchQuery.getPageable().getPageSize());
if (searchQuery.getFilter() != null) {
requestBuilder.setFilter(searchQuery.getFilter());
}
if(searchQuery.getFilter() != null){
requestBuilder.setFilter(searchQuery.getFilter());
}
if (noFields) {
requestBuilder.setNoFields();
}
return requestBuilder.execute().actionGet().getScrollId();
}
if(noFields){
requestBuilder.setNoFields();
}
return requestBuilder.execute().actionGet().getScrollId();
}
@Override
public <T> Page<T> scroll(String scrollId, long scrollTimeInMillis, ResultsMapper<T> resultsMapper) {
SearchResponse response = client.prepareSearchScroll(scrollId)
.setScroll(TimeValue.timeValueMillis(scrollTimeInMillis)).execute().actionGet();
return resultsMapper.mapResults(response);
}
@Override
public <T> Page<T> scroll(String scrollId, long scrollTimeInMillis, ResultsMapper<T> resultsMapper) {
SearchResponse response = client.prepareSearchScroll(scrollId)
.setScroll(TimeValue.timeValueMillis(scrollTimeInMillis))
.execute().actionGet();
return resultsMapper.mapResults(response);
}
@Override
public <T> Page<T> moreLikeThis(MoreLikeThisQuery query, Class<T> clazz) {
int startRecord = 0;
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
String indexName = isNotBlank(query.getIndexName()) ? query.getIndexName() : persistentEntity.getIndexName();
String type = isNotBlank(query.getType()) ? query.getType() : persistentEntity.getIndexType();
@Override
public <T> Page<T> moreLikeThis(MoreLikeThisQuery query, Class<T> clazz) {
int startRecord = 0;
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
String indexName = isNotBlank(query.getIndexName())? query.getIndexName(): persistentEntity.getIndexName();
String type = isNotBlank(query.getType())? query.getType() : persistentEntity.getIndexType();
Assert.notNull(indexName, "No 'indexName' defined for MoreLikeThisQuery");
Assert.notNull(type, "No 'type' defined for MoreLikeThisQuery");
Assert.notNull(query.getId(), "No document id defined for MoreLikeThisQuery");
Assert.notNull(indexName,"No 'indexName' defined for MoreLikeThisQuery");
Assert.notNull(type, "No 'type' defined for MoreLikeThisQuery");
Assert.notNull(query.getId(), "No document id defined for MoreLikeThisQuery");
MoreLikeThisRequestBuilder requestBuilder = client.prepareMoreLikeThis(indexName, type, query.getId());
MoreLikeThisRequestBuilder requestBuilder =
client.prepareMoreLikeThis(indexName,type, query.getId());
if (query.getPageable() != null) {
startRecord = query.getPageable().getPageNumber() * query.getPageable().getPageSize();
requestBuilder.setSearchSize(query.getPageable().getPageSize());
}
requestBuilder.setSearchFrom(startRecord);
if(query.getPageable() != null){
startRecord = query.getPageable().getPageNumber() * query.getPageable().getPageSize();
requestBuilder.setSearchSize(query.getPageable().getPageSize());
}
requestBuilder.setSearchFrom(startRecord);
if (isNotEmpty(query.getSearchIndices())) {
requestBuilder.setSearchIndices(toArray(query.getSearchIndices()));
}
if (isNotEmpty(query.getSearchTypes())) {
requestBuilder.setSearchTypes(toArray(query.getSearchTypes()));
}
if (isNotEmpty(query.getFields())) {
requestBuilder.setField(toArray(query.getFields()));
}
if (isNotBlank(query.getRouting())) {
requestBuilder.setRouting(query.getRouting());
}
if (query.getPercentTermsToMatch() != null) {
requestBuilder.setPercentTermsToMatch(query.getPercentTermsToMatch());
}
if (query.getMinTermFreq() != null) {
requestBuilder.setMinTermFreq(query.getMinTermFreq());
}
if (query.getMaxQueryTerms() != null) {
requestBuilder.maxQueryTerms(query.getMaxQueryTerms());
}
if (isNotEmpty(query.getStopWords())) {
requestBuilder.setStopWords(toArray(query.getStopWords()));
}
if (query.getMinDocFreq() != null) {
requestBuilder.setMinDocFreq(query.getMinDocFreq());
}
if (query.getMaxDocFreq() != null) {
requestBuilder.setMaxDocFreq(query.getMaxDocFreq());
}
if (query.getMinWordLen() != null) {
requestBuilder.setMinWordLen(query.getMinWordLen());
}
if (query.getMaxWordLen() != null) {
requestBuilder.setMaxWordLen(query.getMaxWordLen());
}
if (query.getBoostTerms() != null) {
requestBuilder.setBoostTerms(query.getBoostTerms());
}
if(isNotEmpty(query.getSearchIndices())){
requestBuilder.setSearchIndices(toArray(query.getSearchIndices()));
}
if(isNotEmpty(query.getSearchTypes())){
requestBuilder.setSearchTypes(toArray(query.getSearchTypes()));
}
if(isNotEmpty(query.getFields())){
requestBuilder.setField(toArray(query.getFields()));
}
if(isNotBlank(query.getRouting())){
requestBuilder.setRouting(query.getRouting());
}
if(query.getPercentTermsToMatch() != null){
requestBuilder.setPercentTermsToMatch(query.getPercentTermsToMatch());
}
if(query.getMinTermFreq() != null){
requestBuilder.setMinTermFreq(query.getMinTermFreq());
}
if(query.getMaxQueryTerms() != null){
requestBuilder.maxQueryTerms(query.getMaxQueryTerms());
}
if(isNotEmpty(query.getStopWords())){
requestBuilder.setStopWords(toArray(query.getStopWords()));
}
if(query.getMinDocFreq() != null){
requestBuilder.setMinDocFreq(query.getMinDocFreq());
}
if(query.getMaxDocFreq() != null){
requestBuilder.setMaxDocFreq(query.getMaxDocFreq());
}
if(query.getMinWordLen() != null){
requestBuilder.setMinWordLen(query.getMinWordLen());
}
if(query.getMaxWordLen() != null){
requestBuilder.setMaxWordLen(query.getMaxWordLen());
}
if(query.getBoostTerms() != null){
requestBuilder.setBoostTerms(query.getBoostTerms());
}
SearchResponse response = requestBuilder.execute().actionGet();
return mapResults(response, clazz, query.getPageable());
}
SearchResponse response = requestBuilder.execute().actionGet();
return mapResults(response, clazz, query.getPageable());
}
private SearchResponse doSearch(SearchRequestBuilder searchRequest, QueryBuilder query, FilterBuilder filter,
SortBuilder sortBuilder) {
if (filter != null) {
searchRequest.setFilter(filter);
}
private SearchResponse doSearch(SearchRequestBuilder searchRequest, QueryBuilder query, FilterBuilder filter, SortBuilder sortBuilder){
if(filter != null){
searchRequest.setFilter(filter);
}
if (sortBuilder != null) {
searchRequest.addSort(sortBuilder);
}
if(sortBuilder != null){
searchRequest.addSort(sortBuilder);
}
return searchRequest.setQuery(query).execute().actionGet();
}
return searchRequest.setQuery(query).execute().actionGet();
}
private <T> boolean createIndexIfNotCreated(Class<T> clazz) {
return indexExists(getPersistentEntityFor(clazz).getIndexName()) || createIndexWithSettings(clazz);
}
private <T> boolean createIndexIfNotCreated(Class<T> clazz) {
return indexExists(getPersistentEntityFor(clazz).getIndexName()) || createIndexWithSettings(clazz);
}
private boolean indexExists(String indexName) {
return client.admin().indices().exists(indicesExistsRequest(indexName)).actionGet().isExists();
}
private boolean indexExists(String indexName) {
return client.admin()
.indices()
.exists(indicesExistsRequest(indexName)).actionGet().isExists();
}
private <T> boolean createIndexWithSettings(Class<T> clazz) {
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
return client.admin().indices()
.create(Requests.createIndexRequest(persistentEntity.getIndexName()).settings(getSettings(persistentEntity)))
.actionGet().isAcknowledged();
}
private <T> boolean createIndexWithSettings(Class<T> clazz) {
ElasticsearchPersistentEntity<T> persistentEntity = getPersistentEntityFor(clazz);
return client.admin().indices().create(Requests.createIndexRequest(persistentEntity.getIndexName()).
settings(getSettings(persistentEntity))).actionGet().isAcknowledged();
}
private <T> Map getSettings(ElasticsearchPersistentEntity<T> persistentEntity) {
return new MapBuilder<String, String>().put("index.number_of_shards", String.valueOf(persistentEntity.getShards()))
.put("index.number_of_replicas", String.valueOf(persistentEntity.getReplicas()))
.put("index.refresh_interval", persistentEntity.getRefreshInterval())
.put("index.store.type", persistentEntity.getIndexStoreType()).map();
}
private <T> Map getSettings(ElasticsearchPersistentEntity<T> persistentEntity) {
return new MapBuilder<String, String>()
.put("index.number_of_shards", String.valueOf(persistentEntity.getShards()))
.put("index.number_of_replicas", String.valueOf(persistentEntity.getReplicas()))
.put("index.refresh_interval", persistentEntity.getRefreshInterval())
.put("index.store.type", persistentEntity.getIndexStoreType())
.map();
}
private <T> SearchRequestBuilder prepareSearch(Query query, Class<T> clazz) {
if (query.getIndices().isEmpty()) {
query.addIndices(retrieveIndexNameFromPersistentEntity(clazz));
}
if (query.getTypes().isEmpty()) {
query.addTypes(retrieveTypeFromPersistentEntity(clazz));
}
return prepareSearch(query);
}
private <T> SearchRequestBuilder prepareSearch(Query query, Class<T> clazz){
if(query.getIndices().isEmpty()){
query.addIndices(retrieveIndexNameFromPersistentEntity(clazz));
}
if(query.getTypes().isEmpty()){
query.addTypes(retrieveTypeFromPersistentEntity(clazz));
}
return prepareSearch(query);
}
private SearchRequestBuilder prepareSearch(Query query) {
Assert.notNull(query.getIndices(), "No index defined for Query");
Assert.notNull(query.getTypes(), "No type defined for Query");
private SearchRequestBuilder prepareSearch(Query query){
Assert.notNull(query.getIndices(), "No index defined for Query");
Assert.notNull(query.getTypes(), "No type defined for Query");
int startRecord = 0;
SearchRequestBuilder searchRequestBuilder = client.prepareSearch(toArray(query.getIndices()))
.setSearchType(DFS_QUERY_THEN_FETCH).setTypes(toArray(query.getTypes()));
int startRecord = 0;
SearchRequestBuilder searchRequestBuilder = client.prepareSearch(toArray(query.getIndices()))
.setSearchType(DFS_QUERY_THEN_FETCH)
.setTypes(toArray(query.getTypes()));
if (query.getPageable() != null) {
startRecord = query.getPageable().getPageNumber() * query.getPageable().getPageSize();
searchRequestBuilder.setSize(query.getPageable().getPageSize());
}
searchRequestBuilder.setFrom(startRecord);
if(query.getPageable() != null){
startRecord = query.getPageable().getPageNumber() * query.getPageable().getPageSize();
searchRequestBuilder.setSize(query.getPageable().getPageSize());
}
searchRequestBuilder.setFrom(startRecord);
if (!query.getFields().isEmpty()) {
searchRequestBuilder.addFields(toArray(query.getFields()));
}
if (query.getSort() != null) {
for (Sort.Order order : query.getSort()) {
searchRequestBuilder.addSort(order.getProperty(), order.getDirection() == Sort.Direction.DESC ? SortOrder.DESC
: SortOrder.ASC);
}
}
return searchRequestBuilder;
}
if(!query.getFields().isEmpty()){
searchRequestBuilder.addFields(toArray(query.getFields()));
}
private IndexRequestBuilder prepareIndex(IndexQuery query) {
try {
String indexName = isBlank(query.getIndexName()) ? retrieveIndexNameFromPersistentEntity(query.getObject()
.getClass())[0] : query.getIndexName();
String type = isBlank(query.getType()) ? retrieveTypeFromPersistentEntity(query.getObject().getClass())[0]
: query.getType();
if(query.getSort() != null){
for(Sort.Order order : query.getSort()){
searchRequestBuilder.addSort(order.getProperty(), order.getDirection() == Sort.Direction.DESC? SortOrder.DESC : SortOrder.ASC);
}
}
return searchRequestBuilder;
}
IndexRequestBuilder indexRequestBuilder = client.prepareIndex(indexName, type, query.getId()).setSource(
objectMapper.writeValueAsString(query.getObject()));
private IndexRequestBuilder prepareIndex(IndexQuery query){
try {
String indexName = isBlank(query.getIndexName())?
retrieveIndexNameFromPersistentEntity(query.getObject().getClass())[0] : query.getIndexName();
String type = isBlank(query.getType())?
retrieveTypeFromPersistentEntity(query.getObject().getClass())[0] : query.getType();
if (query.getVersion() != null) {
indexRequestBuilder.setVersion(query.getVersion());
indexRequestBuilder.setVersionType(EXTERNAL);
}
return indexRequestBuilder;
} catch (IOException e) {
throw new ElasticsearchException("failed to index the document [id: " + query.getId() + "]", e);
}
}
IndexRequestBuilder indexRequestBuilder = client.prepareIndex(indexName,type,query.getId())
.setSource(objectMapper.writeValueAsString(query.getObject()));
public void refresh(String indexName, boolean waitForOperation) {
client.admin().indices().refresh(refreshRequest(indexName).waitForOperations(waitForOperation)).actionGet();
}
if(query.getVersion() != null){
indexRequestBuilder.setVersion(query.getVersion());
indexRequestBuilder.setVersionType(EXTERNAL);
}
return indexRequestBuilder;
} catch (IOException e) {
throw new ElasticsearchException("failed to index the document [id: " + query.getId() +"]",e);
}
}
public <T> void refresh(Class<T> clazz, boolean waitForOperation) {
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
client.admin().indices()
.refresh(refreshRequest(persistentEntity.getIndexName()).waitForOperations(waitForOperation)).actionGet();
}
public void refresh(String indexName, boolean waitForOperation) {
client.admin().indices()
.refresh(refreshRequest(indexName).waitForOperations(waitForOperation)).actionGet();
}
private ElasticsearchPersistentEntity getPersistentEntityFor(Class clazz) {
Assert.isTrue(clazz.isAnnotationPresent(Document.class), "Unable to identify index name. " + clazz.getSimpleName()
+ " is not a Document. Make sure the document class is annotated with @Document(indexName=\"foo\")");
return elasticsearchConverter.getMappingContext().getPersistentEntity(clazz);
}
public <T> void refresh(Class<T> clazz, boolean waitForOperation) {
ElasticsearchPersistentEntity persistentEntity = getPersistentEntityFor(clazz);
client.admin().indices()
.refresh(refreshRequest(persistentEntity.getIndexName()).waitForOperations(waitForOperation)).actionGet();
}
private String[] retrieveIndexNameFromPersistentEntity(Class clazz) {
return new String[] { getPersistentEntityFor(clazz).getIndexName() };
}
private ElasticsearchPersistentEntity getPersistentEntityFor(Class clazz){
Assert.isTrue(clazz.isAnnotationPresent(Document.class), "Unable to identify index name. " +
clazz.getSimpleName() + " is not a Document. Make sure the document class is annotated with @Document(indexName=\"foo\")");
return elasticsearchConverter.getMappingContext().getPersistentEntity(clazz);
}
private String[] retrieveTypeFromPersistentEntity(Class clazz) {
return new String[] { getPersistentEntityFor(clazz).getIndexType() };
}
private String[] retrieveIndexNameFromPersistentEntity(Class clazz){
return new String[]{getPersistentEntityFor(clazz).getIndexName()};
}
private <T> Page<T> mapResults(SearchResponse response, final Class<T> elementType, final Pageable pageable) {
ResultsMapper<T> resultsMapper = new ResultsMapper<T>() {
@Override
public Page<T> mapResults(SearchResponse response) {
long totalHits = response.getHits().totalHits();
List<T> results = new ArrayList<T>();
for (SearchHit hit : response.getHits()) {
if (hit != null) {
results.add(mapResult(hit.sourceAsString(), elementType));
}
}
return new PageImpl<T>(results, pageable, totalHits);
}
};
return resultsMapper.mapResults(response);
}
private String[] retrieveTypeFromPersistentEntity(Class clazz){
return new String[]{getPersistentEntityFor(clazz).getIndexType()};
}
private List<String> extractIds(SearchResponse response) {
List<String> ids = new ArrayList<String>();
for (SearchHit hit : response.getHits()) {
if (hit != null) {
ids.add(hit.getId());
}
}
return ids;
}
private <T> Page<T> mapResults(SearchResponse response, final Class<T> elementType,final Pageable pageable){
ResultsMapper<T> resultsMapper = new ResultsMapper<T>(){
@Override
public Page<T> mapResults(SearchResponse response) {
long totalHits = response.getHits().totalHits();
List<T> results = new ArrayList<T>();
for (SearchHit hit : response.getHits()) {
if (hit != null) {
results.add(mapResult(hit.sourceAsString(), elementType));
}
}
return new PageImpl<T>(results, pageable, totalHits);
}
};
return resultsMapper.mapResults(response);
}
private <T> T mapResult(String source, Class<T> clazz) {
if (isBlank(source)) {
return null;
}
try {
return objectMapper.readValue(source, clazz);
} catch (IOException e) {
throw new ElasticsearchException("failed to map source [ " + source + "] to class " + clazz.getSimpleName(), e);
}
}
private List<String> extractIds(SearchResponse response){
List<String> ids = new ArrayList<String>();
for (SearchHit hit : response.getHits()) {
if (hit != null) {
ids.add(hit.getId());
}
}
return ids;
}
private static String[] toArray(List<String> values) {
String[] valuesAsArray = new String[values.size()];
return values.toArray(valuesAsArray);
private <T> T mapResult(String source, Class<T> clazz){
if(isBlank(source)){
return null;
}
try {
return objectMapper.readValue(source, clazz);
} catch (IOException e) {
throw new ElasticsearchException("failed to map source [ " + source + "] to class " + clazz.getSimpleName() , e);
}
}
private static String[] toArray(List<String> values){
String[] valuesAsArray = new String[values.size()];
return values.toArray(valuesAsArray);
}
}
}

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch.core;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.mapping.model.SimpleTypeHolder;
@ -36,95 +35,86 @@ import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder;
class MappingBuilder {
private static SimpleTypeHolder SIMPLE_TYPE_HOLDER = new SimpleTypeHolder();
private static SimpleTypeHolder SIMPLE_TYPE_HOLDER = new SimpleTypeHolder();
static XContentBuilder buildMapping(Class clazz, String indexType, String idFieldName) throws IOException {
XContentBuilder xContentBuilder = jsonBuilder()
.startObject().startObject(indexType).startObject("properties");
static XContentBuilder buildMapping(Class clazz, String indexType, String idFieldName) throws IOException {
XContentBuilder xContentBuilder = jsonBuilder().startObject().startObject(indexType).startObject("properties");
mapEntity(xContentBuilder, clazz, true, idFieldName, EMPTY);
mapEntity(xContentBuilder, clazz, true, idFieldName, EMPTY);
return xContentBuilder.endObject().endObject().endObject();
}
return xContentBuilder.endObject().endObject().endObject();
}
private static void mapEntity(XContentBuilder xContentBuilder,
Class clazz,
boolean isRootObject,
String idFieldName,
String nestedObjectFieldName) throws IOException{
private static void mapEntity(XContentBuilder xContentBuilder, Class clazz, boolean isRootObject, String idFieldName,
String nestedObjectFieldName) throws IOException {
java.lang.reflect.Field[] fields = clazz.getDeclaredFields();
java.lang.reflect.Field[] fields = clazz.getDeclaredFields();
if(!isRootObject && isAnyPropertyAnnotatedAsField(fields)){
xContentBuilder.startObject(nestedObjectFieldName)
.field("type", "object")
.startObject("properties");
}
if (!isRootObject && isAnyPropertyAnnotatedAsField(fields)) {
xContentBuilder.startObject(nestedObjectFieldName).field("type", "object").startObject("properties");
}
for(java.lang.reflect.Field field : fields){
if(isEntity(field)){
mapEntity(xContentBuilder, field.getType(), false, EMPTY, field.getName());
}
Field fieldAnnotation = field.getAnnotation(Field.class);
if(isRootObject && fieldAnnotation != null && isIdField(field, idFieldName)){
applyDefaultIdFieldMapping(xContentBuilder, field);
}else if(fieldAnnotation != null){
applyFieldAnnotationMapping(xContentBuilder, field, fieldAnnotation);
}
}
for (java.lang.reflect.Field field : fields) {
if (isEntity(field)) {
mapEntity(xContentBuilder, field.getType(), false, EMPTY, field.getName());
}
Field fieldAnnotation = field.getAnnotation(Field.class);
if (isRootObject && fieldAnnotation != null && isIdField(field, idFieldName)) {
applyDefaultIdFieldMapping(xContentBuilder, field);
} else if (fieldAnnotation != null) {
applyFieldAnnotationMapping(xContentBuilder, field, fieldAnnotation);
}
}
if(!isRootObject && isAnyPropertyAnnotatedAsField(fields)){
xContentBuilder.endObject().endObject();
}
if (!isRootObject && isAnyPropertyAnnotatedAsField(fields)) {
xContentBuilder.endObject().endObject();
}
}
}
private static void applyDefaultIdFieldMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field) throws IOException {
xContentBuilder.startObject(field.getName())
.field("type", "string")
.field("index", "not_analyzed")
.endObject();
}
private static void applyDefaultIdFieldMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field)
throws IOException {
xContentBuilder.startObject(field.getName()).field("type", "string").field("index", "not_analyzed").endObject();
}
private static void applyFieldAnnotationMapping(XContentBuilder xContentBuilder,
java.lang.reflect.Field field,
Field fieldAnnotation) throws IOException {
xContentBuilder.startObject(field.getName());
xContentBuilder.field("store", fieldAnnotation.store());
if(isNotBlank(fieldAnnotation.type())){
xContentBuilder.field("type", fieldAnnotation.type());
}
if(isNotBlank(fieldAnnotation.index())){
xContentBuilder.field("index", fieldAnnotation.index());
}
if(isNotBlank(fieldAnnotation.searchAnalyzer())){
xContentBuilder.field("search_analyzer", fieldAnnotation.searchAnalyzer());
}
if(isNotBlank(fieldAnnotation.indexAnalyzer())){
xContentBuilder.field("index_analyzer", fieldAnnotation.indexAnalyzer());
}
xContentBuilder.endObject();
}
private static void applyFieldAnnotationMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field,
Field fieldAnnotation) throws IOException {
xContentBuilder.startObject(field.getName());
xContentBuilder.field("store", fieldAnnotation.store());
if (isNotBlank(fieldAnnotation.type())) {
xContentBuilder.field("type", fieldAnnotation.type());
}
if (isNotBlank(fieldAnnotation.index())) {
xContentBuilder.field("index", fieldAnnotation.index());
}
if (isNotBlank(fieldAnnotation.searchAnalyzer())) {
xContentBuilder.field("search_analyzer", fieldAnnotation.searchAnalyzer());
}
if (isNotBlank(fieldAnnotation.indexAnalyzer())) {
xContentBuilder.field("index_analyzer", fieldAnnotation.indexAnalyzer());
}
xContentBuilder.endObject();
}
private static boolean isEntity(java.lang.reflect.Field field) {
TypeInformation typeInformation = ClassTypeInformation.from(field.getType());
TypeInformation<?> actualType = typeInformation.getActualType();
boolean isComplexType = actualType == null ? false : !SIMPLE_TYPE_HOLDER.isSimpleType(actualType.getType());
return isComplexType && !actualType.isCollectionLike() && !Map.class.isAssignableFrom(typeInformation.getType());
}
private static boolean isEntity(java.lang.reflect.Field field) {
TypeInformation typeInformation = ClassTypeInformation.from(field.getType());
TypeInformation<?> actualType = typeInformation.getActualType();
boolean isComplexType = actualType == null ? false : !SIMPLE_TYPE_HOLDER.isSimpleType(actualType.getType());
return isComplexType && !actualType.isCollectionLike() && !Map.class.isAssignableFrom(typeInformation.getType());
}
private static boolean isAnyPropertyAnnotatedAsField(java.lang.reflect.Field[] fields){
if(fields != null){
for(java.lang.reflect.Field field : fields){
if (field.isAnnotationPresent(Field.class)){
return true;
}
}
}
return false;
}
private static boolean isAnyPropertyAnnotatedAsField(java.lang.reflect.Field[] fields) {
if (fields != null) {
for (java.lang.reflect.Field field : fields) {
if (field.isAnnotationPresent(Field.class)) {
return true;
}
}
}
return false;
}
private static boolean isIdField(java.lang.reflect.Field field, String idFieldName){
return idFieldName.equals(field.getName());
}
private static boolean isIdField(java.lang.reflect.Field field, String idFieldName) {
return idFieldName.equals(field.getName());
}
}

View File

@ -20,6 +20,7 @@ import org.springframework.data.domain.Page;
/**
* ResultsMapper
*
* @param <T>
*
* @author Rizwan Idrees
@ -29,6 +30,6 @@ import org.springframework.data.domain.Page;
public interface ResultsMapper<T> {
Page<T> mapResults(SearchResponse response);
Page<T> mapResults(SearchResponse response);
}

View File

@ -25,7 +25,7 @@ import org.springframework.core.convert.converter.Converter;
import java.util.Date;
/**
* DateTimeConverters
* DateTimeConverters
*
* @author Rizwan Idrees
* @author Mohsin Husen
@ -33,7 +33,7 @@ import java.util.Date;
public final class DateTimeConverters {
private static DateTimeFormatter formatter = ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC);
private static DateTimeFormatter formatter = ISODateTimeFormat.dateTime().withZone(DateTimeZone.UTC);
public enum JodaDateTimeConverter implements Converter<ReadableInstant, String> {
INSTANCE;

View File

@ -21,26 +21,26 @@ import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersiste
import org.springframework.data.mapping.context.MappingContext;
/**
* ElasticsearchConverter
* ElasticsearchConverter
*
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public interface ElasticsearchConverter{
public interface ElasticsearchConverter {
/**
* Returns the underlying {@link org.springframework.data.mapping.context.MappingContext} used by the converter.
*
* @return never {@literal null}
*/
MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> getMappingContext();
/**
* Returns the underlying {@link org.springframework.data.mapping.context.MappingContext} used by the converter.
*
* @return never {@literal null}
*/
MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> getMappingContext();
/**
* Returns the underlying {@link org.springframework.core.convert.ConversionService} used by the converter.
*
* @return never {@literal null}.
*/
ConversionService getConversionService();
/**
* Returns the underlying {@link org.springframework.core.convert.ConversionService} used by the converter.
*
* @return never {@literal null}.
*/
ConversionService getConversionService();
}

View File

@ -27,28 +27,29 @@ import org.springframework.data.mapping.context.MappingContext;
import org.springframework.util.Assert;
/**
* MappingElasticsearchConverter
* MappingElasticsearchConverter
*
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class MappingElasticsearchConverter implements ElasticsearchConverter, ApplicationContextAware{
public class MappingElasticsearchConverter implements ElasticsearchConverter, ApplicationContextAware {
private final MappingContext<? extends ElasticsearchPersistentEntity<?>,ElasticsearchPersistentProperty> mappingContext;
private final MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext;
private final GenericConversionService conversionService;
@SuppressWarnings("unused")
private ApplicationContext applicationContext;
public MappingElasticsearchConverter(MappingContext<? extends ElasticsearchPersistentEntity<?>,ElasticsearchPersistentProperty> mappingContext) {
public MappingElasticsearchConverter(
MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext) {
Assert.notNull(mappingContext);
this.mappingContext = mappingContext;
this.conversionService = new DefaultConversionService();
}
@Override
public MappingContext<? extends ElasticsearchPersistentEntity<?>,ElasticsearchPersistentProperty> getMappingContext() {
public MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> getMappingContext() {
return mappingContext;
}

View File

@ -16,6 +16,7 @@
package org.springframework.data.elasticsearch.core.mapping;
import org.springframework.data.mapping.PersistentEntity;
/**
* ElasticsearchPersistentEntity
*
@ -26,10 +27,16 @@ import org.springframework.data.mapping.PersistentEntity;
public interface ElasticsearchPersistentEntity<T> extends PersistentEntity<T, ElasticsearchPersistentProperty> {
String getIndexName();
String getIndexType();
short getShards();
short getReplicas();
String getRefreshInterval();
String getIndexStoreType();
ElasticsearchPersistentProperty getVersionProperty();
String getIndexType();
short getShards();
short getReplicas();
String getRefreshInterval();
String getIndexStoreType();
ElasticsearchPersistentProperty getVersionProperty();
}

View File

@ -17,24 +17,25 @@ package org.springframework.data.elasticsearch.core.mapping;
import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mapping.PersistentProperty;
/**
* ElasticsearchPersistentProperty
* ElasticsearchPersistentProperty
*
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public interface ElasticsearchPersistentProperty extends PersistentProperty<ElasticsearchPersistentProperty>{
public interface ElasticsearchPersistentProperty extends PersistentProperty<ElasticsearchPersistentProperty> {
String getFieldName();
String getFieldName();
public enum PropertyToFieldNameConverter implements Converter<ElasticsearchPersistentProperty, String> {
public enum PropertyToFieldNameConverter implements Converter<ElasticsearchPersistentProperty, String> {
INSTANCE;
INSTANCE;
public String convert(ElasticsearchPersistentProperty source) {
return source.getFieldName();
}
}
public String convert(ElasticsearchPersistentProperty source) {
return source.getFieldName();
}
}
}

View File

@ -39,75 +39,76 @@ import static org.springframework.util.StringUtils.hasText;
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class SimpleElasticsearchPersistentEntity<T> extends BasicPersistentEntity<T, ElasticsearchPersistentProperty> implements
ElasticsearchPersistentEntity<T>, ApplicationContextAware {
public class SimpleElasticsearchPersistentEntity<T> extends BasicPersistentEntity<T, ElasticsearchPersistentProperty>
implements ElasticsearchPersistentEntity<T>, ApplicationContextAware {
private final StandardEvaluationContext context;
private String indexName;
private String indexType;
private short shards;
private short replicas;
private String refreshInterval;
private String indexStoreType;
private final StandardEvaluationContext context;
private String indexName;
private String indexType;
private short shards;
private short replicas;
private String refreshInterval;
private String indexStoreType;
public SimpleElasticsearchPersistentEntity(TypeInformation<T> typeInformation) {
super(typeInformation);
this.context = new StandardEvaluationContext();
Class<T> clazz = typeInformation.getType();
if(clazz.isAnnotationPresent(Document.class)){
Document document = clazz.getAnnotation(Document.class);
Assert.hasText(document.indexName(), " Unknown indexName. Make sure the indexName is defined. e.g @Document(indexName=\"foo\")");
this.indexName = typeInformation.getType().getAnnotation(Document.class).indexName();
this.indexType = hasText(document.type())? document.type() : clazz.getSimpleName().toLowerCase(Locale.ENGLISH);
this.shards = typeInformation.getType().getAnnotation(Document.class).shards();
this.replicas = typeInformation.getType().getAnnotation(Document.class).replicas();
this.refreshInterval = typeInformation.getType().getAnnotation(Document.class).refreshInterval();
this.indexStoreType = typeInformation.getType().getAnnotation(Document.class).indexStoreType();
}
}
public SimpleElasticsearchPersistentEntity(TypeInformation<T> typeInformation) {
super(typeInformation);
this.context = new StandardEvaluationContext();
Class<T> clazz = typeInformation.getType();
if (clazz.isAnnotationPresent(Document.class)) {
Document document = clazz.getAnnotation(Document.class);
Assert.hasText(document.indexName(),
" Unknown indexName. Make sure the indexName is defined. e.g @Document(indexName=\"foo\")");
this.indexName = typeInformation.getType().getAnnotation(Document.class).indexName();
this.indexType = hasText(document.type()) ? document.type() : clazz.getSimpleName().toLowerCase(Locale.ENGLISH);
this.shards = typeInformation.getType().getAnnotation(Document.class).shards();
this.replicas = typeInformation.getType().getAnnotation(Document.class).replicas();
this.refreshInterval = typeInformation.getType().getAnnotation(Document.class).refreshInterval();
this.indexStoreType = typeInformation.getType().getAnnotation(Document.class).indexStoreType();
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context.addPropertyAccessor(new BeanFactoryAccessor());
context.setBeanResolver(new BeanFactoryResolver(applicationContext));
context.setRootObject(applicationContext);
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context.addPropertyAccessor(new BeanFactoryAccessor());
context.setBeanResolver(new BeanFactoryResolver(applicationContext));
context.setRootObject(applicationContext);
}
@Override
public String getIndexName() {
return indexName;
}
@Override
public String getIndexName() {
return indexName;
}
@Override
public String getIndexType() {
return indexType;
}
@Override
public String getIndexType() {
return indexType;
}
@Override
public String getIndexStoreType() {
return indexStoreType;
}
@Override
public String getIndexStoreType() {
return indexStoreType;
}
@Override
public short getShards() {
return shards;
}
@Override
public short getShards() {
return shards;
}
@Override
public short getReplicas() {
return replicas;
}
@Override
public short getReplicas() {
return replicas;
}
@Override
public String getRefreshInterval() {
return refreshInterval;
}
@Override
public String getRefreshInterval() {
return refreshInterval;
}
@Override
public void addPersistentProperty(ElasticsearchPersistentProperty property) {
super.addPersistentProperty(property);
if(property.isVersionProperty()){
Assert.isTrue(property.getType() == Long.class, "Version property should be Long");
}
}
@Override
public void addPersistentProperty(ElasticsearchPersistentProperty property) {
super.addPersistentProperty(property);
if (property.isVersionProperty()) {
Assert.isTrue(property.getType() == Long.class, "Version property should be Long");
}
}
}

View File

@ -31,8 +31,8 @@ import java.util.Set;
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class SimpleElasticsearchPersistentProperty extends AnnotationBasedPersistentProperty<ElasticsearchPersistentProperty> implements
ElasticsearchPersistentProperty {
public class SimpleElasticsearchPersistentProperty extends
AnnotationBasedPersistentProperty<ElasticsearchPersistentProperty> implements ElasticsearchPersistentProperty {
private static final Set<Class<?>> SUPPORTED_ID_TYPES = new HashSet<Class<?>>();
private static final Set<String> SUPPORTED_ID_PROPERTY_NAMES = new HashSet<String>();
@ -40,11 +40,11 @@ public class SimpleElasticsearchPersistentProperty extends AnnotationBasedPersis
static {
SUPPORTED_ID_TYPES.add(String.class);
SUPPORTED_ID_PROPERTY_NAMES.add("id");
SUPPORTED_ID_PROPERTY_NAMES.add("documentId");
SUPPORTED_ID_PROPERTY_NAMES.add("documentId");
}
public SimpleElasticsearchPersistentProperty(Field field, PropertyDescriptor propertyDescriptor,
PersistentEntity<?, ElasticsearchPersistentProperty> owner, SimpleTypeHolder simpleTypeHolder) {
PersistentEntity<?, ElasticsearchPersistentProperty> owner, SimpleTypeHolder simpleTypeHolder) {
super(field, propertyDescriptor, owner, simpleTypeHolder);
}
@ -58,7 +58,7 @@ public class SimpleElasticsearchPersistentProperty extends AnnotationBasedPersis
return super.isIdProperty() || SUPPORTED_ID_PROPERTY_NAMES.contains(getFieldName());
}
@Override
@Override
protected Association<ElasticsearchPersistentProperty> createAssociation() {
return null;
}

View File

@ -30,73 +30,73 @@ import static org.apache.commons.collections.CollectionUtils.addAll;
* @author Rizwan Idrees
* @author Mohsin Husen
*/
abstract class AbstractQuery implements Query{
abstract class AbstractQuery implements Query {
protected Pageable pageable = DEFAULT_PAGE;
protected Sort sort;
protected List<String> indices = new ArrayList<String>();
protected List<String> types = new ArrayList<String>();
protected List<String> fields = new ArrayList<String>();
protected Pageable pageable = DEFAULT_PAGE;
protected Sort sort;
protected List<String> indices = new ArrayList<String>();
protected List<String> types = new ArrayList<String>();
protected List<String> fields = new ArrayList<String>();
@Override
public Sort getSort() {
return this.sort;
}
@Override
public Sort getSort() {
return this.sort;
}
@Override
public Pageable getPageable() {
return this.pageable;
}
@Override
public Pageable getPageable() {
return this.pageable;
}
@Override
public final <T extends Query> T setPageable(Pageable pageable) {
Assert.notNull(pageable);
this.pageable = pageable;
return (T) this.addSort(pageable.getSort());
}
@Override
public final <T extends Query> T setPageable(Pageable pageable) {
Assert.notNull(pageable);
this.pageable = pageable;
return (T) this.addSort(pageable.getSort());
}
@Override
public void addFields(String...fields) {
addAll(this.fields, fields);
}
@Override
public void addFields(String... fields) {
addAll(this.fields, fields);
}
@Override
public List<String> getFields() {
return fields;
}
@Override
public List<String> getFields() {
return fields;
}
@Override
public List<String> getIndices() {
return indices;
}
@Override
public List<String> getIndices() {
return indices;
}
@Override
public void addIndices(String... indices) {
addAll(this.indices,indices);
}
@Override
public void addIndices(String... indices) {
addAll(this.indices, indices);
}
@Override
public void addTypes(String... types) {
addAll(this.types,types);
}
@Override
public void addTypes(String... types) {
addAll(this.types, types);
}
@Override
public List<String> getTypes() {
return types;
}
@Override
public List<String> getTypes() {
return types;
}
@SuppressWarnings("unchecked")
public final <T extends Query> T addSort(Sort sort) {
if (sort == null) {
return (T) this;
}
@SuppressWarnings("unchecked")
public final <T extends Query> T addSort(Sort sort) {
if (sort == null) {
return (T) this;
}
if (this.sort == null) {
this.sort = sort;
} else {
this.sort = this.sort.and(sort);
}
if (this.sort == null) {
this.sort = sort;
} else {
this.sort = this.sort.and(sort);
}
return (T) this;
}
return (T) this;
}
}

View File

@ -251,11 +251,10 @@ public class Criteria {
* @return
*/
public Criteria fuzzy(String s) {
criteria.add(new CriteriaEntry(OperationKey.FUZZY, s));
return this;
criteria.add(new CriteriaEntry(OperationKey.FUZZY, s));
return this;
}
/**
* Crates new CriteriaEntry allowing native elasticsearch expressions
*
@ -342,11 +341,10 @@ public class Criteria {
*/
public Criteria in(Iterable<?> values) {
Assert.notNull(values, "Collection of 'in' values must not be null");
criteria.add(new CriteriaEntry(OperationKey.IN, values));
criteria.add(new CriteriaEntry(OperationKey.IN, values));
return this;
}
private void assertNoBlankInWildcardedQuery(String searchString, boolean leadingWildcard, boolean trailingWildcard) {
if (StringUtils.contains(searchString, CRITERIA_VALUE_SEPERATOR)) {
throw new InvalidDataAccessApiUsageException("Cannot constructQuery '" + (leadingWildcard ? "*" : "") + "\""
@ -384,13 +382,13 @@ public class Criteria {
return this.negating;
}
public boolean isAnd(){
return AND_OPERATOR == getConjunctionOperator();
}
public boolean isAnd() {
return AND_OPERATOR == getConjunctionOperator();
}
public boolean isOr(){
return OR_OPERATOR == getConjunctionOperator();
}
public boolean isOr() {
return OR_OPERATOR == getConjunctionOperator();
}
public float getBoost() {
return this.boost;
@ -431,7 +429,7 @@ public class Criteria {
public static class CriteriaEntry {
private OperationKey key;
private OperationKey key;
private Object value;
CriteriaEntry(OperationKey key, Object value) {

View File

@ -15,67 +15,67 @@
*/
package org.springframework.data.elasticsearch.core.query;
import org.springframework.data.domain.Pageable;
import org.springframework.util.Assert;
/**
* CriteriaQuery
* CriteriaQuery
*
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class CriteriaQuery extends AbstractQuery{
public class CriteriaQuery extends AbstractQuery {
private Criteria criteria;
private CriteriaQuery() {
}
private Criteria criteria;
public CriteriaQuery(Criteria criteria) {
this(criteria, null);
}
private CriteriaQuery() {
}
public CriteriaQuery(Criteria criteria, Pageable pageable) {
this.criteria = criteria;
this.pageable = pageable;
if (pageable != null) {
this.addSort(pageable.getSort());
}
}
public CriteriaQuery(Criteria criteria) {
this(criteria, null);
}
public static final Query fromQuery(CriteriaQuery source) {
return fromQuery(source, new CriteriaQuery());
}
public CriteriaQuery(Criteria criteria, Pageable pageable) {
this.criteria = criteria;
this.pageable = pageable;
if (pageable != null) {
this.addSort(pageable.getSort());
}
}
public static <T extends CriteriaQuery> T fromQuery(CriteriaQuery source, T destination) {
if (source == null || destination == null) {
return null;
}
public static final Query fromQuery(CriteriaQuery source) {
return fromQuery(source, new CriteriaQuery());
}
if (source.getCriteria() != null) {
destination.addCriteria(source.getCriteria());
}
public static <T extends CriteriaQuery> T fromQuery(CriteriaQuery source, T destination) {
if (source == null || destination == null) {
return null;
}
if (source.getSort() != null) {
destination.addSort(source.getSort());
}
if (source.getCriteria() != null) {
destination.addCriteria(source.getCriteria());
}
return destination;
}
if (source.getSort() != null) {
destination.addSort(source.getSort());
}
@SuppressWarnings("unchecked")
public final <T extends CriteriaQuery> T addCriteria(Criteria criteria) {
Assert.notNull(criteria, "Cannot add null criteria.");
if (this.criteria == null) {
this.criteria = criteria;
} else {
this.criteria.and(criteria);
}
return (T) this;
}
return destination;
}
public Criteria getCriteria() {
return this.criteria;
}
@SuppressWarnings("unchecked")
public final <T extends CriteriaQuery> T addCriteria(Criteria criteria) {
Assert.notNull(criteria, "Cannot add null criteria.");
if (this.criteria == null) {
this.criteria = criteria;
} else {
this.criteria.and(criteria);
}
return (T) this;
}
public Criteria getCriteria() {
return this.criteria;
}
}

View File

@ -15,23 +15,23 @@
*/
package org.springframework.data.elasticsearch.core.query;
import org.elasticsearch.index.query.QueryBuilder;
/**
* DeleteQuery
*
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class DeleteQuery{
public class DeleteQuery {
private QueryBuilder query;
private QueryBuilder query;
public QueryBuilder getQuery() {
return query;
}
public QueryBuilder getQuery() {
return query;
}
public void setQuery(QueryBuilder query) {
this.query = query;
}
public void setQuery(QueryBuilder query) {
this.query = query;
}
}

View File

@ -16,20 +16,20 @@
package org.springframework.data.elasticsearch.core.query;
/**
* GetQuery
* GetQuery
*
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class GetQuery{
public class GetQuery {
private String id;
private String id;
public String getId() {
return id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setId(String id) {
this.id = id;
}
}

View File

@ -22,51 +22,51 @@ package org.springframework.data.elasticsearch.core.query;
* @author Mohsin Husen
*/
public class IndexQuery{
public class IndexQuery {
private String id;
private Object object;
private Long version;
private String indexName;
private String type;
private String id;
private Object object;
private Long version;
private String indexName;
private String type;
public String getId() {
return id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setId(String id) {
this.id = id;
}
public Object getObject() {
return object;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
public void setObject(Object object) {
this.object = object;
}
public Long getVersion() {
return version;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public void setVersion(Long version) {
this.version = version;
}
public String getIndexName() {
return indexName;
}
public String getIndexName() {
return indexName;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
public String getType() {
return type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void setType(String type) {
this.type = type;
}
}

View File

@ -32,157 +32,157 @@ import static org.springframework.data.elasticsearch.core.query.Query.DEFAULT_PA
public class MoreLikeThisQuery {
private String id;
private String indexName;
private String type;
private List<String> searchIndices = new ArrayList<String>();
private List<String> searchTypes = new ArrayList<String>();
private List<String> fields = new ArrayList<String>();
private String routing;
private Float percentTermsToMatch;
private Integer minTermFreq;
private Integer maxQueryTerms;
private List<String> stopWords = new ArrayList<String>();
private Integer minDocFreq;
private Integer maxDocFreq;
private Integer minWordLen;
private Integer maxWordLen;
private Float boostTerms;
private Pageable pageable = DEFAULT_PAGE;
private String id;
private String indexName;
private String type;
private List<String> searchIndices = new ArrayList<String>();
private List<String> searchTypes = new ArrayList<String>();
private List<String> fields = new ArrayList<String>();
private String routing;
private Float percentTermsToMatch;
private Integer minTermFreq;
private Integer maxQueryTerms;
private List<String> stopWords = new ArrayList<String>();
private Integer minDocFreq;
private Integer maxDocFreq;
private Integer minWordLen;
private Integer maxWordLen;
private Float boostTerms;
private Pageable pageable = DEFAULT_PAGE;
public String getId() {
return id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setId(String id) {
this.id = id;
}
public String getIndexName() {
return indexName;
}
public String getIndexName() {
return indexName;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
public void setIndexName(String indexName) {
this.indexName = indexName;
}
public String getType() {
return type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void setType(String type) {
this.type = type;
}
public List<String> getSearchIndices() {
return searchIndices;
}
public List<String> getSearchIndices() {
return searchIndices;
}
public void addSearchIndices(String...searchIndices) {
addAll(this.searchIndices, searchIndices);
}
public void addSearchIndices(String... searchIndices) {
addAll(this.searchIndices, searchIndices);
}
public List<String> getSearchTypes() {
return searchTypes;
}
public List<String> getSearchTypes() {
return searchTypes;
}
public void addSearchTypes(String...searchTypes) {
addAll(this.searchTypes, searchTypes);
}
public void addSearchTypes(String... searchTypes) {
addAll(this.searchTypes, searchTypes);
}
public List<String> getFields() {
return fields;
}
public List<String> getFields() {
return fields;
}
public void addFields(String...fields) {
addAll(this.fields,fields);
}
public void addFields(String... fields) {
addAll(this.fields, fields);
}
public String getRouting() {
return routing;
}
public String getRouting() {
return routing;
}
public void setRouting(String routing) {
this.routing = routing;
}
public void setRouting(String routing) {
this.routing = routing;
}
public Float getPercentTermsToMatch() {
return percentTermsToMatch;
}
public Float getPercentTermsToMatch() {
return percentTermsToMatch;
}
public void setPercentTermsToMatch(Float percentTermsToMatch) {
this.percentTermsToMatch = percentTermsToMatch;
}
public void setPercentTermsToMatch(Float percentTermsToMatch) {
this.percentTermsToMatch = percentTermsToMatch;
}
public Integer getMinTermFreq() {
return minTermFreq;
}
public Integer getMinTermFreq() {
return minTermFreq;
}
public void setMinTermFreq(Integer minTermFreq) {
this.minTermFreq = minTermFreq;
}
public void setMinTermFreq(Integer minTermFreq) {
this.minTermFreq = minTermFreq;
}
public Integer getMaxQueryTerms() {
return maxQueryTerms;
}
public Integer getMaxQueryTerms() {
return maxQueryTerms;
}
public void setMaxQueryTerms(Integer maxQueryTerms) {
this.maxQueryTerms = maxQueryTerms;
}
public void setMaxQueryTerms(Integer maxQueryTerms) {
this.maxQueryTerms = maxQueryTerms;
}
public List<String> getStopWords() {
return stopWords;
}
public List<String> getStopWords() {
return stopWords;
}
public void addStopWords(String...stopWords) {
addAll(this.stopWords,stopWords);
}
public void addStopWords(String... stopWords) {
addAll(this.stopWords, stopWords);
}
public Integer getMinDocFreq() {
return minDocFreq;
}
public Integer getMinDocFreq() {
return minDocFreq;
}
public void setMinDocFreq(Integer minDocFreq) {
this.minDocFreq = minDocFreq;
}
public void setMinDocFreq(Integer minDocFreq) {
this.minDocFreq = minDocFreq;
}
public Integer getMaxDocFreq() {
return maxDocFreq;
}
public Integer getMaxDocFreq() {
return maxDocFreq;
}
public void setMaxDocFreq(Integer maxDocFreq) {
this.maxDocFreq = maxDocFreq;
}
public void setMaxDocFreq(Integer maxDocFreq) {
this.maxDocFreq = maxDocFreq;
}
public Integer getMinWordLen() {
return minWordLen;
}
public Integer getMinWordLen() {
return minWordLen;
}
public void setMinWordLen(Integer minWordLen) {
this.minWordLen = minWordLen;
}
public void setMinWordLen(Integer minWordLen) {
this.minWordLen = minWordLen;
}
public Integer getMaxWordLen() {
return maxWordLen;
}
public Integer getMaxWordLen() {
return maxWordLen;
}
public void setMaxWordLen(Integer maxWordLen) {
this.maxWordLen = maxWordLen;
}
public void setMaxWordLen(Integer maxWordLen) {
this.maxWordLen = maxWordLen;
}
public Float getBoostTerms() {
return boostTerms;
}
public Float getBoostTerms() {
return boostTerms;
}
public void setBoostTerms(Float boostTerms) {
this.boostTerms = boostTerms;
}
public void setBoostTerms(Float boostTerms) {
this.boostTerms = boostTerms;
}
public Pageable getPageable() {
return pageable;
}
public Pageable getPageable() {
return pageable;
}
public void setPageable(Pageable pageable) {
this.pageable = pageable;
}
public void setPageable(Pageable pageable) {
this.pageable = pageable;
}
}

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch.core.query;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.sort.SortBuilder;
@ -29,26 +28,25 @@ import org.elasticsearch.search.sort.SortBuilder;
*/
public class NativeSearchQuery extends AbstractQuery implements SearchQuery {
private QueryBuilder query;
private FilterBuilder filter;
private SortBuilder sort;
private QueryBuilder query;
private FilterBuilder filter;
private SortBuilder sort;
public NativeSearchQuery(QueryBuilder query, FilterBuilder filter, SortBuilder sort) {
this.query = query;
this.filter = filter;
this.sort = sort;
}
public NativeSearchQuery(QueryBuilder query, FilterBuilder filter, SortBuilder sort) {
this.query = query;
this.filter = filter;
this.sort = sort;
}
public QueryBuilder getQuery() {
return query;
}
public QueryBuilder getQuery() {
return query;
}
public FilterBuilder getFilter() {
return filter;
}
public FilterBuilder getFilter() {
return filter;
}
public SortBuilder getElasticsearchSort() {
return sort;
}
public SortBuilder getElasticsearchSort() {
return sort;
}
}

View File

@ -30,63 +30,63 @@ import org.springframework.data.domain.Pageable;
public class NativeSearchQueryBuilder {
private QueryBuilder queryBuilder;
private FilterBuilder filterBuilder;
private SortBuilder sortBuilder;
private Pageable pageable;
private String[] indices;
private String[] types;
private String[] fields;
private QueryBuilder queryBuilder;
private FilterBuilder filterBuilder;
private SortBuilder sortBuilder;
private Pageable pageable;
private String[] indices;
private String[] types;
private String[] fields;
public NativeSearchQueryBuilder withQuery(QueryBuilder queryBuilder){
this.queryBuilder = queryBuilder;
return this;
}
public NativeSearchQueryBuilder withQuery(QueryBuilder queryBuilder) {
this.queryBuilder = queryBuilder;
return this;
}
public NativeSearchQueryBuilder withFilter(FilterBuilder filterBuilder){
this.filterBuilder = filterBuilder;
return this;
}
public NativeSearchQueryBuilder withFilter(FilterBuilder filterBuilder) {
this.filterBuilder = filterBuilder;
return this;
}
public NativeSearchQueryBuilder withSort(SortBuilder sortBuilder){
this.sortBuilder = sortBuilder;
return this;
}
public NativeSearchQueryBuilder withSort(SortBuilder sortBuilder) {
this.sortBuilder = sortBuilder;
return this;
}
public NativeSearchQueryBuilder withPageable(Pageable pageable){
this.pageable = pageable;
return this;
}
public NativeSearchQueryBuilder withPageable(Pageable pageable) {
this.pageable = pageable;
return this;
}
public NativeSearchQueryBuilder withIndices(String... indices){
this.indices = indices;
return this;
}
public NativeSearchQueryBuilder withIndices(String... indices) {
this.indices = indices;
return this;
}
public NativeSearchQueryBuilder withTypes(String... types){
this.types = types;
return this;
}
public NativeSearchQueryBuilder withTypes(String... types) {
this.types = types;
return this;
}
public NativeSearchQueryBuilder withFields(String... fields){
this.fields = fields;
return this;
}
public NativeSearchQueryBuilder withFields(String... fields) {
this.fields = fields;
return this;
}
public NativeSearchQuery build(){
NativeSearchQuery nativeSearchQuery = new NativeSearchQuery(queryBuilder,filterBuilder,sortBuilder);
if(pageable != null){
nativeSearchQuery.setPageable(pageable);
}
if(indices != null) {
nativeSearchQuery.addIndices(indices);
}
if(types != null) {
nativeSearchQuery.addTypes(types);
}
if(fields != null) {
nativeSearchQuery.addFields(fields);
}
return nativeSearchQuery;
}
public NativeSearchQuery build() {
NativeSearchQuery nativeSearchQuery = new NativeSearchQuery(queryBuilder, filterBuilder, sortBuilder);
if (pageable != null) {
nativeSearchQuery.setPageable(pageable);
}
if (indices != null) {
nativeSearchQuery.addIndices(indices);
}
if (types != null) {
nativeSearchQuery.addTypes(types);
}
if (fields != null) {
nativeSearchQuery.addFields(fields);
}
return nativeSearchQuery;
}
}

View File

@ -15,12 +15,12 @@
*/
package org.springframework.data.elasticsearch.core.query;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import java.util.List;
/**
* Query
*
@ -29,85 +29,83 @@ import java.util.List;
*/
public interface Query {
public static final int DEFAULT_PAGE_SIZE = 10;
public static final Pageable DEFAULT_PAGE = new PageRequest(0, DEFAULT_PAGE_SIZE);
public static final int DEFAULT_PAGE_SIZE = 10;
public static final Pageable DEFAULT_PAGE = new PageRequest(0, DEFAULT_PAGE_SIZE);
/**
* restrict result to entries on given page. Corresponds to the 'start' and 'rows' parameter in elasticsearch
*
* @param pageable
* @return
*/
<T extends Query> T setPageable(Pageable pageable);
/**
* restrict result to entries on given page. Corresponds to the 'start' and 'rows' parameter in elasticsearch
*
* @param pageable
* @return
*/
<T extends Query> T setPageable(Pageable pageable);
/**
* Get filter queries if defined
*
* @return
*/
// List<FilterQuery> getFilterQueries();
/**
* Get page settings if defined
*
* @return
*/
Pageable getPageable();
/**
* Add {@link org.springframework.data.domain.Sort} to query
*
* @param sort
* @return
*/
<T extends Query> T addSort(Sort sort);
/**
* Get filter queries if defined
*
* @return
*/
//List<FilterQuery> getFilterQueries();
/**
* @return null if not set
*/
Sort getSort();
/**
* Get page settings if defined
*
* @return
*/
Pageable getPageable();
/**
* Get Indices to be searched
*
* @return
*/
List<String> getIndices();
/**
* Add Indices to be added as part of search request
*
* @param indices
*/
void addIndices(String... indices);
/**
* Add types to be searched
*
* @param types
*/
void addTypes(String... types);
/**
* Add {@link org.springframework.data.domain.Sort} to query
*
* @param sort
* @return
*/
<T extends Query> T addSort(Sort sort);
/**
* Get types to be searched
*
* @return
*/
List<String> getTypes();
/**
* @return null if not set
*/
Sort getSort();
/**
* Add fields to be added as part of search request
*
* @param fields
*/
void addFields(String... fields);
/**
* Get Indices to be searched
* @return
*/
List<String> getIndices();
/**
* Add Indices to be added as part of search request
* @param indices
*/
void addIndices(String...indices);
/**
* Add types to be searched
* @param types
*/
void addTypes(String...types);
/**
* Get types to be searched
* @return
*/
List<String> getTypes();
/**
* Add fields to be added as part of search request
* @param fields
*/
void addFields(String...fields);
/**
* Get fields to be returned as part of search request
* @return
*/
List<String> getFields();
/**
* Get fields to be returned as part of search request
*
* @return
*/
List<String> getFields();
}

View File

@ -18,6 +18,7 @@ package org.springframework.data.elasticsearch.core.query;
import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.sort.SortBuilder;
/**
* NativeSearchQuery
*
@ -26,7 +27,9 @@ import org.elasticsearch.search.sort.SortBuilder;
* @author Artur Konczak
*/
public interface SearchQuery extends Query {
QueryBuilder getQuery();
FilterBuilder getFilter();
SortBuilder getElasticsearchSort();
QueryBuilder getQuery();
FilterBuilder getFilter();
SortBuilder getElasticsearchSort();
}

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch.core.query;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
@ -25,28 +24,27 @@ import org.springframework.data.domain.Sort;
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class StringQuery extends AbstractQuery{
public class StringQuery extends AbstractQuery {
private String source;
private String source;
public StringQuery(String source) {
this.source = source;
}
public StringQuery(String source) {
this.source = source;
}
public StringQuery(String source, Pageable pageable) {
this.source = source;
this.pageable = pageable;
}
public StringQuery(String source, Pageable pageable) {
this.source = source;
this.pageable = pageable;
}
public StringQuery(String source, Pageable pageable, Sort sort) {
this.pageable = pageable;
this.sort = sort;
this.source = source;
}
public StringQuery(String source, Pageable pageable, Sort sort) {
this.pageable = pageable;
this.sort = sort;
this.source = source;
}
public String getSource() {
return source;
}
public String getSource() {
return source;
}
}

View File

@ -29,6 +29,6 @@ import java.util.List;
*/
public interface ElasticsearchCrudRepository<T, ID extends Serializable> extends PagingAndSortingRepository<T, ID> {
<S extends T> List<S> save(List<S> entities);
<S extends T> List<S> save(List<S> entities);
}

View File

@ -31,15 +31,15 @@ import java.io.Serializable;
* @author Mohsin Husen
*/
@NoRepositoryBean
public interface ElasticsearchRepository<T, ID extends Serializable> extends ElasticsearchCrudRepository<T,ID> {
public interface ElasticsearchRepository<T, ID extends Serializable> extends ElasticsearchCrudRepository<T, ID> {
<S extends T> S index(S entity);
<S extends T> S index(S entity);
Iterable<T> search(QueryBuilder query);
Iterable<T> search(QueryBuilder query);
Page<T> search(QueryBuilder query, Pageable pageable);
Page<T> search(QueryBuilder query, Pageable pageable);
Page<T> search(SearchQuery searchQuery);
Page<T> search(SearchQuery searchQuery);
Page<T> searchSimilar(T entity, SearchQuery searchQuery);
Page<T> searchSimilar(T entity, SearchQuery searchQuery);
}

View File

@ -36,8 +36,8 @@ public class ElasticsearchRepositoryBean<T> extends CdiRepositoryBean<T> {
private final Bean<ElasticsearchOperations> elasticsearchOperationsBean;
public ElasticsearchRepositoryBean(Bean<ElasticsearchOperations> operations, Set<Annotation> qualifiers, Class<T> repositoryType,
BeanManager beanManager) {
public ElasticsearchRepositoryBean(Bean<ElasticsearchOperations> operations, Set<Annotation> qualifiers,
Class<T> repositoryType, BeanManager beanManager) {
super(qualifiers, repositoryType, beanManager);
Assert.notNull(operations, "Cannot create repository with 'null' for ElasticsearchOperations.");
@ -46,7 +46,8 @@ public class ElasticsearchRepositoryBean<T> extends CdiRepositoryBean<T> {
@Override
protected T create(CreationalContext<T> creationalContext, Class<T> repositoryType) {
ElasticsearchOperations elasticsearchOperations = getDependencyInstance(elasticsearchOperationsBean, ElasticsearchOperations.class);
ElasticsearchOperations elasticsearchOperations = getDependencyInstance(elasticsearchOperationsBean,
ElasticsearchOperations.class);
return new ElasticsearchRepositoryFactory(elasticsearchOperations).getRepository(repositoryType);
}

View File

@ -53,24 +53,25 @@ public class ElasticsearchRepositoryExtension extends CdiRepositoryExtensionSupp
}
void afterBeanDiscovery(@Observes AfterBeanDiscovery afterBeanDiscovery, BeanManager beanManager) {
for (Entry<Class<?>, Set<Annotation>> entry : getRepositoryTypes()) {
for (Entry<Class<?>, Set<Annotation>> entry : getRepositoryTypes()) {
Class<?> repositoryType = entry.getKey();
Set<Annotation> qualifiers = entry.getValue();
Bean<?> repositoryBean = createRepositoryBean(repositoryType, qualifiers, beanManager);
afterBeanDiscovery.addBean(repositoryBean);
afterBeanDiscovery.addBean(repositoryBean);
}
}
private <T> Bean<T> createRepositoryBean(Class<T> repositoryType, Set<Annotation> qualifiers, BeanManager beanManager) {
Bean<ElasticsearchOperations> elasticsearchOperationsBean = this.elasticsearchOperationsMap.get(qualifiers.toString());
Bean<ElasticsearchOperations> elasticsearchOperationsBean = this.elasticsearchOperationsMap.get(qualifiers
.toString());
if (elasticsearchOperationsBean == null) {
throw new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.",
ElasticsearchOperations.class.getName(), qualifiers));
ElasticsearchOperations.class.getName(), qualifiers));
}
return new ElasticsearchRepositoryBean<T>(elasticsearchOperationsBean, qualifiers, repositoryType, beanManager);
return new ElasticsearchRepositoryBean<T>(elasticsearchOperationsBean, qualifiers, repositoryType, beanManager);
}
}

View File

@ -21,8 +21,8 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
import java.lang.annotation.Annotation;
/**
* {@link org.springframework.context.annotation.ImportBeanDefinitionRegistrar} implementation to trigger configuration of the {@link EnableElasticsearchRepositories}
* annotation.
* {@link org.springframework.context.annotation.ImportBeanDefinitionRegistrar} implementation to trigger configuration
* of the {@link EnableElasticsearchRepositories} annotation.
*
* @author Rizwan Idrees
* @author Mohsin Husen

View File

@ -23,11 +23,10 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
import org.springframework.data.repository.config.XmlRepositoryConfigurationSource;
import org.w3c.dom.Element;
/**
* {@link org.springframework.data.repository.config.RepositoryConfigurationExtension} implementation to configure Elasticsearch repository configuration support,
* evaluating the {@link EnableElasticsearchRepositories} annotation or the equivalent XML element.
* {@link org.springframework.data.repository.config.RepositoryConfigurationExtension} implementation to configure
* Elasticsearch repository configuration support, evaluating the {@link EnableElasticsearchRepositories} annotation or
* the equivalent XML element.
*
* @author Rizwan Idrees
* @author Mohsin Husen

View File

@ -24,8 +24,8 @@ import org.springframework.data.repository.query.QueryLookupStrategy.Key;
import java.lang.annotation.*;
/**
* Annotation to enable Elasticsearch repositories. Will scan the package of the annotated configuration class for Spring Data
* repositories by default.
* Annotation to enable Elasticsearch repositories. Will scan the package of the annotated configuration class for
* Spring Data repositories by default.
*
* @author Rizwan Idrees
* @author Mohsin Husen
@ -39,7 +39,8 @@ public @interface EnableElasticsearchRepositories {
/**
* Alias for the {@link #basePackages()} attribute. Allows for more concise annotation declarations e.g.:
* {@code @EnableElasticsearchRepositories("org.my.pkg")} instead of {@code @EnableElasticsearchRepositories(basePackages="org.my.pkg")}.
* {@code @EnableElasticsearchRepositories("org.my.pkg")} instead of
* {@code @EnableElasticsearchRepositories(basePackages="org.my.pkg")}.
*/
String[] value() default {};
@ -85,7 +86,8 @@ public @interface EnableElasticsearchRepositories {
String namedQueriesLocation() default "";
/**
* Returns the key of the {@link org.springframework.data.repository.query.QueryLookupStrategy} to be used for lookup queries for query methods. Defaults to
* Returns the key of the {@link org.springframework.data.repository.query.QueryLookupStrategy} to be used for lookup
* queries for query methods. Defaults to
* {@link org.springframework.data.repository.query.QueryLookupStrategy.Key#CREATE_IF_NOT_FOUND}.
*
* @return
@ -93,8 +95,8 @@ public @interface EnableElasticsearchRepositories {
Key queryLookupStrategy() default Key.CREATE_IF_NOT_FOUND;
/**
* Returns the {@link org.springframework.beans.factory.FactoryBean} class to be used for each repository instance. Defaults to
* {@link ElasticsearchRepositoryFactoryBean}.
* Returns the {@link org.springframework.beans.factory.FactoryBean} class to be used for each repository instance.
* Defaults to {@link ElasticsearchRepositoryFactoryBean}.
*
* @return
*/
@ -103,8 +105,8 @@ public @interface EnableElasticsearchRepositories {
// Elasticsearch specific configuration
/**
* Configures the name of the {@link ElasticsearchTemplate} bean definition to be used to create repositories discovered
* through this annotation. Defaults to {@code elasticsearchTemplate}.
* Configures the name of the {@link ElasticsearchTemplate} bean definition to be used to create repositories
* discovered through this annotation. Defaults to {@code elasticsearchTemplate}.
*
* @return
*/

View File

@ -28,17 +28,18 @@ import org.springframework.data.repository.query.RepositoryQuery;
public abstract class AbstractElasticsearchRepositoryQuery implements RepositoryQuery {
protected ElasticsearchQueryMethod queryMethod;
protected ElasticsearchOperations elasticsearchOperations;
protected ElasticsearchQueryMethod queryMethod;
protected ElasticsearchOperations elasticsearchOperations;
public AbstractElasticsearchRepositoryQuery(ElasticsearchQueryMethod queryMethod, ElasticsearchOperations elasticsearchOperations) {
this.queryMethod = queryMethod;
this.elasticsearchOperations = elasticsearchOperations;
}
public AbstractElasticsearchRepositoryQuery(ElasticsearchQueryMethod queryMethod,
ElasticsearchOperations elasticsearchOperations) {
this.queryMethod = queryMethod;
this.elasticsearchOperations = elasticsearchOperations;
}
@Override
public QueryMethod getQueryMethod() {
return queryMethod;
}
@Override
public QueryMethod getQueryMethod() {
return queryMethod;
}
}

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch.repository.query;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty;
import org.springframework.data.elasticsearch.core.query.CriteriaQuery;
@ -25,40 +24,39 @@ import org.springframework.data.repository.query.ParametersParameterAccessor;
import org.springframework.data.repository.query.parser.PartTree;
/**
* ElasticsearchPartQuery
* ElasticsearchPartQuery
*
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class ElasticsearchPartQuery extends AbstractElasticsearchRepositoryQuery{
public class ElasticsearchPartQuery extends AbstractElasticsearchRepositoryQuery {
private final PartTree tree;
private final MappingContext<?, ElasticsearchPersistentProperty> mappingContext;
private final PartTree tree;
private final MappingContext<?, ElasticsearchPersistentProperty> mappingContext;
public ElasticsearchPartQuery(ElasticsearchQueryMethod method, ElasticsearchOperations elasticsearchOperations) {
super(method, elasticsearchOperations);
this.tree = new PartTree(method.getName(), method.getEntityInformation().getJavaType());
this.mappingContext = elasticsearchOperations.getElasticsearchConverter().getMappingContext();
}
public ElasticsearchPartQuery(ElasticsearchQueryMethod method, ElasticsearchOperations elasticsearchOperations) {
super(method, elasticsearchOperations);
this.tree = new PartTree(method.getName(), method.getEntityInformation().getJavaType());
this.mappingContext = elasticsearchOperations.getElasticsearchConverter().getMappingContext();
}
@Override
public Object execute(Object[] parameters) {
ParametersParameterAccessor accessor = new ParametersParameterAccessor(queryMethod.getParameters(), parameters);
CriteriaQuery query = createQuery(accessor);
if (queryMethod.isPageQuery()) {
query.setPageable(accessor.getPageable());
return elasticsearchOperations.queryForPage(query, queryMethod.getEntityInformation().getJavaType());
} else if (queryMethod.isCollectionQuery()) {
if (accessor.getPageable() != null) {
query.setPageable(accessor.getPageable());
}
return elasticsearchOperations.queryForList(query, queryMethod.getEntityInformation().getJavaType());
}
return elasticsearchOperations.queryForObject(query, queryMethod.getEntityInformation().getJavaType());
}
@Override
public Object execute(Object[] parameters) {
ParametersParameterAccessor accessor = new ParametersParameterAccessor(queryMethod.getParameters(), parameters);
CriteriaQuery query = createQuery(accessor);
if(queryMethod.isPageQuery()){
query.setPageable(accessor.getPageable());
return elasticsearchOperations.queryForPage(query, queryMethod.getEntityInformation().getJavaType());
} else if (queryMethod.isCollectionQuery()) {
if(accessor.getPageable() != null){
query.setPageable(accessor.getPageable());
}
return elasticsearchOperations.queryForList(query,queryMethod.getEntityInformation().getJavaType());
}
return elasticsearchOperations.queryForObject(query, queryMethod.getEntityInformation().getJavaType());
}
public CriteriaQuery createQuery(ParametersParameterAccessor accessor) {
return new ElasticsearchQueryCreator(tree, accessor, mappingContext).createQuery();
}
public CriteriaQuery createQuery(ParametersParameterAccessor accessor) {
return new ElasticsearchQueryCreator(tree, accessor, mappingContext).createQuery();
}
}

View File

@ -26,33 +26,35 @@ import org.springframework.util.StringUtils;
import java.lang.reflect.Method;
/**
* ElasticsearchQueryMethod
* ElasticsearchQueryMethod
*
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class ElasticsearchQueryMethod extends QueryMethod {
private final ElasticsearchEntityInformation<?, ?> entityInformation;
private Method method;
private final ElasticsearchEntityInformation<?, ?> entityInformation;
private Method method;
public ElasticsearchQueryMethod(Method method, RepositoryMetadata metadata, ElasticsearchEntityInformationCreator elasticsearchEntityInformationCreator) {
super(method, metadata);
this.entityInformation = elasticsearchEntityInformationCreator.getEntityInformation(metadata.getReturnedDomainClass(method));
this.method = method;
}
public ElasticsearchQueryMethod(Method method, RepositoryMetadata metadata,
ElasticsearchEntityInformationCreator elasticsearchEntityInformationCreator) {
super(method, metadata);
this.entityInformation = elasticsearchEntityInformationCreator.getEntityInformation(metadata
.getReturnedDomainClass(method));
this.method = method;
}
public boolean hasAnnotatedQuery() {
return getQueryAnnotation() != null;
}
public boolean hasAnnotatedQuery() {
return getQueryAnnotation() != null;
}
public String getAnnotatedQuery() {
String query = (String) AnnotationUtils.getValue(getQueryAnnotation(), "value");
return StringUtils.hasText(query) ? query : null;
}
public String getAnnotatedQuery() {
String query = (String) AnnotationUtils.getValue(getQueryAnnotation(), "value");
return StringUtils.hasText(query) ? query : null;
}
private Query getQueryAnnotation() {
return this.method.getAnnotation(Query.class);
}
private Query getQueryAnnotation() {
return this.method.getAnnotation(Query.class);
}
}

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch.repository.query;
import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.convert.DateTimeConverters;
@ -32,74 +31,74 @@ import java.util.regex.Pattern;
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class ElasticsearchStringQuery extends AbstractElasticsearchRepositoryQuery{
public class ElasticsearchStringQuery extends AbstractElasticsearchRepositoryQuery {
private static final Pattern PARAMETER_PLACEHOLDER = Pattern.compile("\\?(\\d+)");
private String query;
private static final Pattern PARAMETER_PLACEHOLDER = Pattern.compile("\\?(\\d+)");
private String query;
private final GenericConversionService conversionService = new GenericConversionService();
private final GenericConversionService conversionService = new GenericConversionService();
{
if (!conversionService.canConvert(java.util.Date.class, String.class)) {
conversionService.addConverter(DateTimeConverters.JavaDateConverter.INSTANCE);
}
if (!conversionService.canConvert(org.joda.time.ReadableInstant.class, String.class)) {
conversionService.addConverter(DateTimeConverters.JodaDateTimeConverter.INSTANCE);
}
if (!conversionService.canConvert(org.joda.time.LocalDateTime.class, String.class)) {
conversionService.addConverter(DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE);
}
{
if (!conversionService.canConvert(java.util.Date.class, String.class)) {
conversionService.addConverter(DateTimeConverters.JavaDateConverter.INSTANCE);
}
if (!conversionService.canConvert(org.joda.time.ReadableInstant.class, String.class)) {
conversionService.addConverter(DateTimeConverters.JodaDateTimeConverter.INSTANCE);
}
if (!conversionService.canConvert(org.joda.time.LocalDateTime.class, String.class)) {
conversionService.addConverter(DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE);
}
}
}
public ElasticsearchStringQuery(ElasticsearchQueryMethod queryMethod, ElasticsearchOperations elasticsearchOperations, String query) {
super(queryMethod, elasticsearchOperations);
Assert.notNull(query, "Query cannot be empty");
this.query = query;
}
public ElasticsearchStringQuery(ElasticsearchQueryMethod queryMethod,
ElasticsearchOperations elasticsearchOperations, String query) {
super(queryMethod, elasticsearchOperations);
Assert.notNull(query, "Query cannot be empty");
this.query = query;
}
@Override
public Object execute(Object[] parameters) {
ParametersParameterAccessor accessor = new ParametersParameterAccessor(queryMethod.getParameters(), parameters);
StringQuery stringQuery = createQuery(accessor);
if(queryMethod.isPageQuery()){
stringQuery.setPageable(accessor.getPageable());
return elasticsearchOperations.queryForPage(stringQuery, queryMethod.getEntityInformation().getJavaType());
} else if(queryMethod.isCollectionQuery()) {
if(accessor.getPageable() != null) {
stringQuery.setPageable(accessor.getPageable());
}
return elasticsearchOperations.queryForList(stringQuery,queryMethod.getEntityInformation().getJavaType());
}
@Override
public Object execute(Object[] parameters) {
ParametersParameterAccessor accessor = new ParametersParameterAccessor(queryMethod.getParameters(), parameters);
StringQuery stringQuery = createQuery(accessor);
if (queryMethod.isPageQuery()) {
stringQuery.setPageable(accessor.getPageable());
return elasticsearchOperations.queryForPage(stringQuery, queryMethod.getEntityInformation().getJavaType());
} else if (queryMethod.isCollectionQuery()) {
if (accessor.getPageable() != null) {
stringQuery.setPageable(accessor.getPageable());
}
return elasticsearchOperations.queryForList(stringQuery, queryMethod.getEntityInformation().getJavaType());
}
return elasticsearchOperations.queryForObject(stringQuery, queryMethod.getEntityInformation().getJavaType());
}
return elasticsearchOperations.queryForObject(stringQuery, queryMethod.getEntityInformation().getJavaType());
}
protected StringQuery createQuery(ParametersParameterAccessor parameterAccessor) {
String queryString = replacePlaceholders(this.query, parameterAccessor);
return new StringQuery(queryString);
}
protected StringQuery createQuery(ParametersParameterAccessor parameterAccessor) {
String queryString = replacePlaceholders(this.query, parameterAccessor);
return new StringQuery(queryString);
}
private String replacePlaceholders(String input, ParametersParameterAccessor accessor) {
Matcher matcher = PARAMETER_PLACEHOLDER.matcher(input);
String result = input;
while (matcher.find()) {
String group = matcher.group();
int index = Integer.parseInt(matcher.group(1));
result = result.replace(group, getParameterWithIndex(accessor, index));
}
return result;
}
private String replacePlaceholders(String input, ParametersParameterAccessor accessor) {
Matcher matcher = PARAMETER_PLACEHOLDER.matcher(input);
String result = input;
while (matcher.find()) {
String group = matcher.group();
int index = Integer.parseInt(matcher.group(1));
result = result.replace(group, getParameterWithIndex(accessor, index));
}
return result;
}
private String getParameterWithIndex(ParametersParameterAccessor accessor, int index) {
Object parameter = accessor.getBindableValue(index);
if (parameter == null) {
return "null";
}
if (conversionService.canConvert(parameter.getClass(), String.class)) {
return conversionService.convert(parameter, String.class);
}
return parameter.toString();
}
private String getParameterWithIndex(ParametersParameterAccessor accessor, int index) {
Object parameter = accessor.getBindableValue(index);
if (parameter == null) {
return "null";
}
if (conversionService.canConvert(parameter.getClass(), String.class)) {
return conversionService.convert(parameter, String.class);
}
return parameter.toString();
}
}

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch.repository.query.parser;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty;
@ -37,100 +36,102 @@ import java.util.Iterator;
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class ElasticsearchQueryCreator extends AbstractQueryCreator<CriteriaQuery,CriteriaQuery>{
public class ElasticsearchQueryCreator extends AbstractQueryCreator<CriteriaQuery, CriteriaQuery> {
private final MappingContext<?, ElasticsearchPersistentProperty> context;
private final MappingContext<?, ElasticsearchPersistentProperty> context;
public ElasticsearchQueryCreator(PartTree tree, ParameterAccessor parameters, MappingContext<?, ElasticsearchPersistentProperty> context) {
super(tree, parameters);
this.context = context;
}
public ElasticsearchQueryCreator(PartTree tree, ParameterAccessor parameters,
MappingContext<?, ElasticsearchPersistentProperty> context) {
super(tree, parameters);
this.context = context;
}
public ElasticsearchQueryCreator(PartTree tree, MappingContext<?, ElasticsearchPersistentProperty> context) {
super(tree);
this.context = context;
}
public ElasticsearchQueryCreator(PartTree tree, MappingContext<?, ElasticsearchPersistentProperty> context) {
super(tree);
this.context = context;
}
@Override
protected CriteriaQuery create(Part part, Iterator<Object> iterator) {
PersistentPropertyPath<ElasticsearchPersistentProperty> path = context.getPersistentPropertyPath(part.getProperty());
return new CriteriaQuery(from(part.getType(),
new Criteria(path.toDotPath(ElasticsearchPersistentProperty.PropertyToFieldNameConverter.INSTANCE)), iterator));
}
@Override
protected CriteriaQuery create(Part part, Iterator<Object> iterator) {
PersistentPropertyPath<ElasticsearchPersistentProperty> path = context
.getPersistentPropertyPath(part.getProperty());
return new CriteriaQuery(from(part.getType(),
new Criteria(path.toDotPath(ElasticsearchPersistentProperty.PropertyToFieldNameConverter.INSTANCE)), iterator));
}
@Override
protected CriteriaQuery and(Part part, CriteriaQuery base, Iterator<Object> iterator) {
if (base == null) {
return create(part, iterator);
}
PersistentPropertyPath<ElasticsearchPersistentProperty> path = context.getPersistentPropertyPath(part.getProperty());
return base.addCriteria(from(part.getType(),
new Criteria(path.toDotPath(ElasticsearchPersistentProperty.PropertyToFieldNameConverter.INSTANCE)), iterator));
}
@Override
protected CriteriaQuery and(Part part, CriteriaQuery base, Iterator<Object> iterator) {
if (base == null) {
return create(part, iterator);
}
PersistentPropertyPath<ElasticsearchPersistentProperty> path = context
.getPersistentPropertyPath(part.getProperty());
return base.addCriteria(from(part.getType(),
new Criteria(path.toDotPath(ElasticsearchPersistentProperty.PropertyToFieldNameConverter.INSTANCE)), iterator));
}
@Override
protected CriteriaQuery or(CriteriaQuery base, CriteriaQuery query) {
return new CriteriaQuery(base.getCriteria().or(query.getCriteria()));
}
@Override
protected CriteriaQuery or(CriteriaQuery base, CriteriaQuery query) {
return new CriteriaQuery(base.getCriteria().or(query.getCriteria()));
}
@Override
protected CriteriaQuery complete(CriteriaQuery query, Sort sort) {
if (query == null) {
return null;
}
return query.addSort(sort);
}
@Override
protected CriteriaQuery complete(CriteriaQuery query, Sort sort) {
if (query == null) {
return null;
}
return query.addSort(sort);
}
private Criteria from(Part.Type type, Criteria instance, Iterator<?> parameters) {
Criteria criteria = instance;
if (criteria == null) {
criteria = new Criteria();
}
switch (type) {
case TRUE:
return criteria.is(true);
case FALSE:
return criteria.is(false);
case SIMPLE_PROPERTY:
return criteria.is(parameters.next());
case NEGATING_SIMPLE_PROPERTY:
return criteria.is(parameters.next()).not();
case REGEX:
return criteria.expression(parameters.next().toString());
case LIKE:
case STARTING_WITH:
return criteria.startsWith(parameters.next().toString());
case ENDING_WITH:
return criteria.endsWith(parameters.next().toString());
case CONTAINING:
return criteria.contains(parameters.next().toString());
case AFTER:
case GREATER_THAN:
case GREATER_THAN_EQUAL:
return criteria.greaterThanEqual(parameters.next());
case BEFORE:
case LESS_THAN:
case LESS_THAN_EQUAL:
return criteria.lessThanEqual(parameters.next());
case BETWEEN:
return criteria.between(parameters.next(), parameters.next());
case IN:
return criteria.in(asArray(parameters.next()));
case NOT_IN:
return criteria.in(asArray(parameters.next())).not();
default:
throw new InvalidDataAccessApiUsageException("Illegal criteria found '" + type + "'.");
}
}
private Criteria from(Part.Type type, Criteria instance, Iterator<?> parameters) {
Criteria criteria = instance;
if (criteria == null) {
criteria = new Criteria();
}
switch (type) {
case TRUE:
return criteria.is(true);
case FALSE:
return criteria.is(false);
case SIMPLE_PROPERTY:
return criteria.is(parameters.next());
case NEGATING_SIMPLE_PROPERTY:
return criteria.is(parameters.next()).not();
case REGEX:
return criteria.expression(parameters.next().toString());
case LIKE:
case STARTING_WITH:
return criteria.startsWith(parameters.next().toString());
case ENDING_WITH:
return criteria.endsWith(parameters.next().toString());
case CONTAINING:
return criteria.contains(parameters.next().toString());
case AFTER:
case GREATER_THAN:
case GREATER_THAN_EQUAL:
return criteria.greaterThanEqual(parameters.next());
case BEFORE:
case LESS_THAN:
case LESS_THAN_EQUAL:
return criteria.lessThanEqual(parameters.next());
case BETWEEN:
return criteria.between(parameters.next(), parameters.next());
case IN:
return criteria.in(asArray(parameters.next()));
case NOT_IN:
return criteria.in(asArray(parameters.next())).not();
default:
throw new InvalidDataAccessApiUsageException("Illegal criteria found '" + type + "'.");
}
}
private Object[] asArray(Object o) {
if (o instanceof Collection) {
return ((Collection<?>) o).toArray();
} else if (o.getClass().isArray()) {
return (Object[]) o;
}
return new Object[] { o };
}
private Object[] asArray(Object o) {
if (o instanceof Collection) {
return ((Collection<?>) o).toArray();
} else if (o.getClass().isArray()) {
return (Object[]) o;
}
return new Object[] { o };
}
}

View File

@ -36,283 +36,273 @@ import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.springframework.data.elasticsearch.core.query.Query.DEFAULT_PAGE;
/**
* Elasticsearch specific repository implementation. Likely to be used as target within {@link ElasticsearchRepositoryFactory}
* Elasticsearch specific repository implementation. Likely to be used as target within
* {@link ElasticsearchRepositoryFactory}
*
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Ryan Henszey
*/
public abstract class AbstractElasticsearchRepository<T,ID extends Serializable> implements ElasticsearchRepository<T, ID> {
public abstract class AbstractElasticsearchRepository<T, ID extends Serializable> implements
ElasticsearchRepository<T, ID> {
protected ElasticsearchOperations elasticsearchOperations;
protected Class<T> entityClass;
protected ElasticsearchEntityInformation<T, ID> entityInformation;
protected ElasticsearchOperations elasticsearchOperations;
protected Class<T> entityClass;
protected ElasticsearchEntityInformation<T, ID> entityInformation;
public AbstractElasticsearchRepository() {
}
public AbstractElasticsearchRepository() {
}
public AbstractElasticsearchRepository(ElasticsearchOperations elasticsearchOperations) {
Assert.notNull(elasticsearchOperations);
this.setElasticsearchOperations(elasticsearchOperations);
}
public AbstractElasticsearchRepository(ElasticsearchOperations elasticsearchOperations) {
Assert.notNull(elasticsearchOperations);
this.setElasticsearchOperations(elasticsearchOperations);
}
public AbstractElasticsearchRepository(ElasticsearchEntityInformation<T, ID> metadata,
ElasticsearchOperations elasticsearchOperations) {
this(elasticsearchOperations);
Assert.notNull(metadata);
this.entityInformation = metadata;
setEntityClass(this.entityInformation.getJavaType());
createIndex();
putMapping();
}
public AbstractElasticsearchRepository(ElasticsearchEntityInformation<T, ID> metadata, ElasticsearchOperations elasticsearchOperations) {
this(elasticsearchOperations);
Assert.notNull(metadata);
this.entityInformation = metadata;
setEntityClass(this.entityInformation.getJavaType());
createIndex();
putMapping();
}
private void createIndex() {
elasticsearchOperations.createIndex(getEntityClass());
}
private void createIndex(){
elasticsearchOperations.createIndex(getEntityClass());
}
private void putMapping() {
elasticsearchOperations.putMapping(getEntityClass());
}
private void putMapping(){
elasticsearchOperations.putMapping(getEntityClass());
}
@Override
public T findOne(ID id) {
GetQuery query = new GetQuery();
query.setId(stringIdRepresentation(id));
return elasticsearchOperations.queryForObject(query, getEntityClass());
}
@Override
public T findOne(ID id) {
GetQuery query = new GetQuery();
query.setId(stringIdRepresentation(id));
return elasticsearchOperations.queryForObject(query, getEntityClass());
}
@Override
public Iterable<T> findAll() {
int itemCount = (int) this.count();
if (itemCount == 0) {
return new PageImpl<T>(Collections.<T> emptyList());
}
return this.findAll(new PageRequest(0, Math.max(1, itemCount)));
}
@Override
public Iterable<T> findAll() {
int itemCount = (int) this.count();
if (itemCount == 0) {
return new PageImpl<T>(Collections.<T> emptyList());
}
return this.findAll(new PageRequest(0, Math.max(1, itemCount)));
}
@Override
public Page<T> findAll(Pageable pageable) {
SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withPageable(pageable).build();
return elasticsearchOperations.queryForPage(query, getEntityClass());
}
@Override
public Page<T> findAll(Pageable pageable) {
SearchQuery query = new NativeSearchQueryBuilder()
.withQuery(matchAllQuery())
.withPageable(pageable)
.build();
return elasticsearchOperations.queryForPage(query, getEntityClass());
}
@Override
public Iterable<T> findAll(Sort sort) {
int itemCount = (int) this.count();
if (itemCount == 0) {
return new PageImpl<T>(Collections.<T> emptyList());
}
SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withPageable(new PageRequest(0, itemCount, sort)).build();
return elasticsearchOperations.queryForPage(query, getEntityClass());
}
@Override
public Iterable<T> findAll(Sort sort) {
int itemCount = (int) this.count();
if (itemCount == 0) {
return new PageImpl<T>(Collections.<T> emptyList());
}
SearchQuery query = new NativeSearchQueryBuilder()
.withQuery(matchAllQuery())
.withPageable(new PageRequest(0,itemCount, sort))
.build();
return elasticsearchOperations.queryForPage(query, getEntityClass());
}
@Override
public Iterable<T> findAll(Iterable<ID> ids) {
SearchQuery query = new NativeSearchQueryBuilder().withQuery(inQuery(entityInformation.getIdAttribute(), ids))
.build();
return elasticsearchOperations.queryForPage(query, getEntityClass());
}
@Override
public Iterable<T> findAll(Iterable<ID> ids) {
SearchQuery query = new NativeSearchQueryBuilder()
.withQuery(inQuery(entityInformation.getIdAttribute(), ids))
.build();
return elasticsearchOperations.queryForPage(query, getEntityClass());
}
@Override
public long count() {
SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
return elasticsearchOperations.count(query, getEntityClass());
}
@Override
public long count() {
SearchQuery query = new NativeSearchQueryBuilder()
.withQuery(matchAllQuery()).build();
return elasticsearchOperations.count(query,getEntityClass());
}
@Override
public <S extends T> S save(S entity) {
Assert.notNull(entity, "Cannot save 'null' entity.");
elasticsearchOperations.index(createIndexQuery(entity));
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
return entity;
}
@Override
public <S extends T> S save(S entity) {
Assert.notNull(entity, "Cannot save 'null' entity.");
elasticsearchOperations.index(createIndexQuery(entity));
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
return entity;
}
public <S extends T> List<S> save(List<S> entities) {
Assert.notNull(entities, "Cannot insert 'null' as a List.");
Assert.notEmpty(entities, "Cannot insert empty List.");
List<IndexQuery> queries = new ArrayList<IndexQuery>();
for (S s : entities) {
queries.add(createIndexQuery(s));
}
elasticsearchOperations.bulkIndex(queries);
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
return entities;
}
public <S extends T> List<S> save(List<S> entities) {
Assert.notNull(entities, "Cannot insert 'null' as a List.");
Assert.notEmpty(entities,"Cannot insert empty List.");
List<IndexQuery> queries = new ArrayList<IndexQuery>();
for(S s:entities){
queries.add(createIndexQuery(s));
}
elasticsearchOperations.bulkIndex(queries);
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
return entities;
}
@Override
public <S extends T> S index(S entity) {
return save(entity);
}
@Override
public <S extends T> S index(S entity) {
return save(entity);
}
@Override
public <S extends T> Iterable<S> save(Iterable<S> entities) {
Assert.notNull(entities, "Cannot insert 'null' as a List.");
if (!(entities instanceof Collection<?>)) {
throw new InvalidDataAccessApiUsageException("Entities have to be inside a collection");
}
List<IndexQuery> queries = new ArrayList<IndexQuery>();
for (S s : entities) {
queries.add(createIndexQuery(s));
}
elasticsearchOperations.bulkIndex(queries);
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
return entities;
}
@Override
public <S extends T> Iterable<S> save(Iterable<S> entities) {
Assert.notNull(entities, "Cannot insert 'null' as a List.");
if (!(entities instanceof Collection<?>)) {
throw new InvalidDataAccessApiUsageException("Entities have to be inside a collection");
}
List<IndexQuery> queries = new ArrayList<IndexQuery>();
for(S s: entities){
queries.add(createIndexQuery(s));
}
elasticsearchOperations.bulkIndex(queries);
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
return entities;
}
@Override
public boolean exists(ID id) {
return findOne(id) != null;
}
@Override
public boolean exists(ID id) {
return findOne(id) != null;
}
@Override
public Iterable<T> search(QueryBuilder query) {
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(query).build();
int count = (int) elasticsearchOperations.count(searchQuery, getEntityClass());
if (count == 0) {
return new PageImpl<T>(Collections.<T> emptyList());
}
searchQuery.setPageable(new PageRequest(0, count));
return elasticsearchOperations.queryForPage(searchQuery, getEntityClass());
}
@Override
public Iterable<T> search(QueryBuilder query) {
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(query).build();
int count = (int) elasticsearchOperations.count(searchQuery, getEntityClass());
if(count == 0){
return new PageImpl<T>(Collections.<T>emptyList());
}
searchQuery.setPageable(new PageRequest(0, count));
return elasticsearchOperations.queryForPage(searchQuery, getEntityClass());
}
@Override
public Page<T> search(QueryBuilder query, Pageable pageable) {
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(query).withPageable(pageable).build();
return elasticsearchOperations.queryForPage(searchQuery, getEntityClass());
}
@Override
public Page<T> search(QueryBuilder query, Pageable pageable) {
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(query)
.withPageable(pageable)
.build();
return elasticsearchOperations.queryForPage(searchQuery, getEntityClass());
}
@Override
public Page<T> search(SearchQuery query) {
return elasticsearchOperations.queryForPage(query, getEntityClass());
}
@Override
public Page<T> search(SearchQuery query){
return elasticsearchOperations.queryForPage(query, getEntityClass());
}
@Override
public Page<T> searchSimilar(T entity, SearchQuery searchQuery) {
Assert.notNull(entity, "Cannot search similar records for 'null'.");
Assert.notNull(searchQuery.getFields(), "Fields cannot be 'null'");
MoreLikeThisQuery query = new MoreLikeThisQuery();
query.setId(stringIdRepresentation(extractIdFromBean(entity)));
query.setPageable(searchQuery.getPageable() != null ? searchQuery.getPageable() : DEFAULT_PAGE);
query.addFields(searchQuery.getFields().toArray(new String[searchQuery.getFields().size()]));
if (!searchQuery.getIndices().isEmpty()) {
query.addSearchIndices(searchQuery.getIndices().toArray(new String[searchQuery.getIndices().size()]));
}
if (!searchQuery.getTypes().isEmpty()) {
query.addSearchTypes(searchQuery.getTypes().toArray(new String[searchQuery.getTypes().size()]));
}
return elasticsearchOperations.moreLikeThis(query, getEntityClass());
}
@Override
public Page<T> searchSimilar(T entity, SearchQuery searchQuery) {
Assert.notNull(entity, "Cannot search similar records for 'null'.");
Assert.notNull(searchQuery.getFields(), "Fields cannot be 'null'");
MoreLikeThisQuery query = new MoreLikeThisQuery();
query.setId(stringIdRepresentation(extractIdFromBean(entity)));
query.setPageable(searchQuery.getPageable() != null ? searchQuery.getPageable() : DEFAULT_PAGE);
query.addFields(searchQuery.getFields().toArray(new String[searchQuery.getFields().size()]));
if(!searchQuery.getIndices().isEmpty()) {
query.addSearchIndices(searchQuery.getIndices().toArray(new String[searchQuery.getIndices().size()]));
}
if(!searchQuery.getTypes().isEmpty()){
query.addSearchTypes(searchQuery.getTypes().toArray(new String[searchQuery.getTypes().size()]));
}
return elasticsearchOperations.moreLikeThis(query, getEntityClass());
}
@Override
public void delete(ID id) {
Assert.notNull(id, "Cannot delete entity with id 'null'.");
elasticsearchOperations.delete(entityInformation.getIndexName(), entityInformation.getType(),
stringIdRepresentation(id));
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
}
@Override
public void delete(T entity) {
Assert.notNull(entity, "Cannot delete 'null' entity.");
delete(extractIdFromBean(entity));
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
}
@Override
public void delete(ID id) {
Assert.notNull(id, "Cannot delete entity with id 'null'.");
elasticsearchOperations.delete(entityInformation.getIndexName(), entityInformation.getType(),stringIdRepresentation(id));
elasticsearchOperations.refresh(entityInformation.getIndexName(),true);
}
@Override
public void delete(Iterable<? extends T> entities) {
Assert.notNull(entities, "Cannot delete 'null' list.");
for (T entity : entities) {
delete(entity);
}
}
@Override
public void delete(T entity) {
Assert.notNull(entity, "Cannot delete 'null' entity.");
delete(extractIdFromBean(entity));
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
}
@Override
public void deleteAll() {
DeleteQuery deleteQuery = new DeleteQuery();
deleteQuery.setQuery(matchAllQuery());
elasticsearchOperations.delete(deleteQuery, getEntityClass());
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
}
@Override
public void delete(Iterable<? extends T> entities) {
Assert.notNull(entities, "Cannot delete 'null' list.");
for (T entity : entities) {
delete(entity);
}
}
private IndexQuery createIndexQuery(T entity) {
IndexQuery query = new IndexQuery();
query.setObject(entity);
query.setId(stringIdRepresentation(extractIdFromBean(entity)));
query.setVersion(extractVersionFromBean(entity));
return query;
}
@Override
public void deleteAll() {
DeleteQuery deleteQuery = new DeleteQuery();
deleteQuery.setQuery(matchAllQuery());
elasticsearchOperations.delete(deleteQuery, getEntityClass());
elasticsearchOperations.refresh(entityInformation.getIndexName(),true);
}
@SuppressWarnings("unchecked")
private Class<T> resolveReturnedClassFromGenericType() {
ParameterizedType parameterizedType = resolveReturnedClassFromGenericType(getClass());
return (Class<T>) parameterizedType.getActualTypeArguments()[0];
}
private IndexQuery createIndexQuery(T entity){
IndexQuery query = new IndexQuery();
query.setObject(entity);
query.setId(stringIdRepresentation(extractIdFromBean(entity)));
query.setVersion(extractVersionFromBean(entity));
return query;
}
private ParameterizedType resolveReturnedClassFromGenericType(Class<?> clazz) {
Object genericSuperclass = clazz.getGenericSuperclass();
if (genericSuperclass instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
Type rawtype = parameterizedType.getRawType();
if (SimpleElasticsearchRepository.class.equals(rawtype)) {
return parameterizedType;
}
}
return resolveReturnedClassFromGenericType(clazz.getSuperclass());
}
@SuppressWarnings("unchecked")
private Class<T> resolveReturnedClassFromGenericType() {
ParameterizedType parameterizedType = resolveReturnedClassFromGenericType(getClass());
return (Class<T>) parameterizedType.getActualTypeArguments()[0];
}
public Class<T> getEntityClass() {
if (!isEntityClassSet()) {
try {
this.entityClass = resolveReturnedClassFromGenericType();
} catch (Exception e) {
throw new InvalidDataAccessApiUsageException("Unable to resolve EntityClass. Please use according setter!", e);
}
}
return entityClass;
}
private ParameterizedType resolveReturnedClassFromGenericType(Class<?> clazz) {
Object genericSuperclass = clazz.getGenericSuperclass();
if (genericSuperclass instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
Type rawtype = parameterizedType.getRawType();
if (SimpleElasticsearchRepository.class.equals(rawtype)) {
return parameterizedType;
}
}
return resolveReturnedClassFromGenericType(clazz.getSuperclass());
}
private boolean isEntityClassSet() {
return entityClass != null;
}
public Class<T> getEntityClass() {
if (!isEntityClassSet()) {
try {
this.entityClass = resolveReturnedClassFromGenericType();
} catch (Exception e) {
throw new InvalidDataAccessApiUsageException("Unable to resolve EntityClass. Please use according setter!", e);
}
}
return entityClass;
}
public final void setEntityClass(Class<T> entityClass) {
Assert.notNull(entityClass, "EntityClass must not be null.");
this.entityClass = entityClass;
}
private boolean isEntityClassSet() {
return entityClass != null;
}
public final void setElasticsearchOperations(ElasticsearchOperations elasticsearchOperations) {
Assert.notNull(elasticsearchOperations, "ElasticsearchOperations must not be null.");
this.elasticsearchOperations = elasticsearchOperations;
}
public final void setEntityClass(Class<T> entityClass) {
Assert.notNull(entityClass, "EntityClass must not be null.");
this.entityClass = entityClass;
}
protected ID extractIdFromBean(T entity) {
if (entityInformation != null) {
return entityInformation.getId(entity);
}
return null;
}
public final void setElasticsearchOperations(ElasticsearchOperations elasticsearchOperations) {
Assert.notNull(elasticsearchOperations, "ElasticsearchOperations must not be null.");
this.elasticsearchOperations = elasticsearchOperations;
}
protected abstract String stringIdRepresentation(ID id);
protected ID extractIdFromBean(T entity) {
if (entityInformation != null) {
return entityInformation.getId(entity);
}
return null;
}
protected abstract String stringIdRepresentation(ID id);
private Long extractVersionFromBean(T entity){
if (entityInformation != null) {
return entityInformation.getVersion(entity);
}
return null;
}
private Long extractVersionFromBean(T entity) {
if (entityInformation != null) {
return entityInformation.getVersion(entity);
}
return null;
}
}

View File

@ -29,7 +29,10 @@ import java.io.Serializable;
public interface ElasticsearchEntityInformation<T, ID extends Serializable> extends EntityInformation<T, ID> {
String getIdAttribute();
String getIndexName();
String getType();
Long getVersion(T entity);
String getIndexName();
String getType();
Long getVersion(T entity);
}

View File

@ -18,7 +18,7 @@ package org.springframework.data.elasticsearch.repository.support;
import java.io.Serializable;
/**
* ElasticsearchEntityInformationCreator
* ElasticsearchEntityInformationCreator
*
* @author Rizwan Idrees
* @author Mohsin Husen

View File

@ -33,7 +33,7 @@ public class ElasticsearchEntityInformationCreatorImpl implements ElasticsearchE
private final MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext;
public ElasticsearchEntityInformationCreatorImpl(
MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext) {
MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext) {
Assert.notNull(mappingContext);
this.mappingContext = mappingContext;
}
@ -41,7 +41,7 @@ public class ElasticsearchEntityInformationCreatorImpl implements ElasticsearchE
@Override
@SuppressWarnings("unchecked")
public <T, ID extends Serializable> ElasticsearchEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
ElasticsearchPersistentEntity<T> persistentEntity = (ElasticsearchPersistentEntity<T>) mappingContext
ElasticsearchPersistentEntity<T> persistentEntity = (ElasticsearchPersistentEntity<T>) mappingContext
.getPersistentEntity(domainClass);
return new MappingElasticsearchEntityInformation<T, ID>(persistentEntity);
}

View File

@ -42,83 +42,80 @@ import org.springframework.util.Assert;
*/
public class ElasticsearchRepositoryFactory extends RepositoryFactorySupport {
private final ElasticsearchOperations elasticsearchOperations;
private final ElasticsearchEntityInformationCreator entityInformationCreator;
private final ElasticsearchOperations elasticsearchOperations;
private final ElasticsearchEntityInformationCreator entityInformationCreator;
public ElasticsearchRepositoryFactory(ElasticsearchOperations elasticsearchOperations) {
Assert.notNull(elasticsearchOperations);
this.elasticsearchOperations = elasticsearchOperations;
this.entityInformationCreator = new ElasticsearchEntityInformationCreatorImpl(elasticsearchOperations
.getElasticsearchConverter().getMappingContext());
}
public ElasticsearchRepositoryFactory(ElasticsearchOperations elasticsearchOperations) {
Assert.notNull(elasticsearchOperations);
this.elasticsearchOperations = elasticsearchOperations;
this.entityInformationCreator = new ElasticsearchEntityInformationCreatorImpl(elasticsearchOperations.getElasticsearchConverter()
.getMappingContext());
}
@Override
public <T, ID extends Serializable> ElasticsearchEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
return entityInformationCreator.getEntityInformation(domainClass);
}
@Override
public <T, ID extends Serializable> ElasticsearchEntityInformation<T, ID> getEntityInformation(Class<T> domainClass) {
return entityInformationCreator.getEntityInformation(domainClass);
}
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Object getTargetRepository(RepositoryMetadata metadata) {
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
protected Object getTargetRepository(RepositoryMetadata metadata) {
ElasticsearchEntityInformation<?, ?> entityInformation = getEntityInformation(metadata.getDomainType());
ElasticsearchEntityInformation<?, ?> entityInformation = getEntityInformation(metadata.getDomainType());
AbstractElasticsearchRepository repository;
AbstractElasticsearchRepository repository;
// Probably a better way to store and look these up.
if (Integer.class.isAssignableFrom(entityInformation.getIdType())
|| Long.class.isAssignableFrom(entityInformation.getIdType())
|| Double.class.isAssignableFrom(entityInformation.getIdType())) {
// logger.debug("Using NumberKeyedRepository for " + metadata.getRepositoryInterface());
repository = new NumberKeyedRepository(getEntityInformation(metadata.getDomainType()), elasticsearchOperations);
} else if (entityInformation.getIdType() == String.class) {
// logger.debug("Using SimpleElasticsearchRepository for " + metadata.getRepositoryInterface());
repository = new SimpleElasticsearchRepository(getEntityInformation(metadata.getDomainType()),
elasticsearchOperations);
} else {
throw new IllegalArgumentException("Unsuppored ID type " + entityInformation.getIdType());
}
repository.setEntityClass(metadata.getDomainType());
//Probably a better way to store and look these up.
if(Integer.class.isAssignableFrom(entityInformation.getIdType()) ||
Long.class.isAssignableFrom(entityInformation.getIdType()) ||
Double.class.isAssignableFrom(entityInformation.getIdType())){
//logger.debug("Using NumberKeyedRepository for " + metadata.getRepositoryInterface());
repository = new NumberKeyedRepository(getEntityInformation(metadata.getDomainType()), elasticsearchOperations);
}
else if (entityInformation.getIdType() == String.class){
//logger.debug("Using SimpleElasticsearchRepository for " + metadata.getRepositoryInterface());
repository = new SimpleElasticsearchRepository(getEntityInformation(metadata.getDomainType()), elasticsearchOperations);
}
else {
throw new IllegalArgumentException("Unsuppored ID type " + entityInformation.getIdType());
}
repository.setEntityClass(metadata.getDomainType());
return repository;
}
return repository;
}
@Override
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
if (isQueryDslRepository(metadata.getRepositoryInterface())) {
throw new IllegalArgumentException("QueryDsl Support has not been implemented yet.");
}
return SimpleElasticsearchRepository.class;
}
@Override
protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata) {
if (isQueryDslRepository(metadata.getRepositoryInterface())) {
throw new IllegalArgumentException("QueryDsl Support has not been implemented yet.");
}
return SimpleElasticsearchRepository.class;
}
private static boolean isQueryDslRepository(Class<?> repositoryInterface) {
return QUERY_DSL_PRESENT && QueryDslPredicateExecutor.class.isAssignableFrom(repositoryInterface);
}
private static boolean isQueryDslRepository(Class<?> repositoryInterface) {
return QUERY_DSL_PRESENT && QueryDslPredicateExecutor.class.isAssignableFrom(repositoryInterface);
}
@Override
protected QueryLookupStrategy getQueryLookupStrategy(QueryLookupStrategy.Key key) {
return new ElasticsearchQueryLookupStrategy();
}
@Override
protected QueryLookupStrategy getQueryLookupStrategy(QueryLookupStrategy.Key key) {
return new ElasticsearchQueryLookupStrategy();
}
private class ElasticsearchQueryLookupStrategy implements QueryLookupStrategy {
private class ElasticsearchQueryLookupStrategy implements QueryLookupStrategy {
@Override
public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, NamedQueries namedQueries) {
@Override
public RepositoryQuery resolveQuery(Method method, RepositoryMetadata metadata, NamedQueries namedQueries) {
ElasticsearchQueryMethod queryMethod = new ElasticsearchQueryMethod(method, metadata, entityInformationCreator);
String namedQueryName = queryMethod.getNamedQueryName();
ElasticsearchQueryMethod queryMethod = new ElasticsearchQueryMethod(method, metadata, entityInformationCreator);
String namedQueryName = queryMethod.getNamedQueryName();
if (namedQueries.hasQuery(namedQueryName)) {
String namedQuery = namedQueries.getQuery(namedQueryName);
return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, namedQuery);
}
else if (queryMethod.hasAnnotatedQuery()) {
return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, queryMethod.getAnnotatedQuery());
}
return new ElasticsearchPartQuery(queryMethod, elasticsearchOperations);
}
}
if (namedQueries.hasQuery(namedQueryName)) {
String namedQuery = namedQueries.getQuery(namedQueryName);
return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, namedQuery);
} else if (queryMethod.hasAnnotatedQuery()) {
return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, queryMethod.getAnnotatedQuery());
}
return new ElasticsearchPartQuery(queryMethod, elasticsearchOperations);
}
}
}

View File

@ -24,13 +24,14 @@ import org.springframework.util.Assert;
import java.io.Serializable;
/**
* Spring {@link org.springframework.beans.factory.FactoryBean} implementation to ease container based configuration for XML namespace and JavaConfig.
* Spring {@link org.springframework.beans.factory.FactoryBean} implementation to ease container based configuration for
* XML namespace and JavaConfig.
*
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class ElasticsearchRepositoryFactoryBean<T extends Repository<S, ID>, S, ID extends Serializable> extends
RepositoryFactoryBeanSupport<T, S, ID> {
RepositoryFactoryBeanSupport<T, S, ID> {
private ElasticsearchOperations operations;
@ -50,14 +51,13 @@ public class ElasticsearchRepositoryFactoryBean<T extends Repository<S, ID>, S,
*/
@Override
public void afterPropertiesSet() {
super.afterPropertiesSet();
super.afterPropertiesSet();
Assert.notNull(operations, "ElasticsearchOperations must be configured!");
}
@Override
protected RepositoryFactorySupport createRepositoryFactory() {
return new ElasticsearchRepositoryFactory(operations);
}
@Override
protected RepositoryFactorySupport createRepositoryFactory() {
return new ElasticsearchRepositoryFactory(operations);
}
}

View File

@ -26,7 +26,8 @@ import org.springframework.data.repository.core.support.AbstractEntityInformatio
import org.springframework.util.Assert;
/**
* Elasticsearch specific implementation of {@link org.springframework.data.repository.core.support.AbstractEntityInformation}
* Elasticsearch specific implementation of
* {@link org.springframework.data.repository.core.support.AbstractEntityInformation}
*
* @param <T>
* @param <ID>
@ -36,71 +37,71 @@ import org.springframework.util.Assert;
* @author Ryan Henszey
*/
public class MappingElasticsearchEntityInformation<T, ID extends Serializable> extends AbstractEntityInformation<T, ID>
implements ElasticsearchEntityInformation<T, ID> {
implements ElasticsearchEntityInformation<T, ID> {
private static final Logger logger = LoggerFactory.getLogger(MappingElasticsearchEntityInformation.class);
private final ElasticsearchPersistentEntity<T> entityMetadata;
private final String indexName;
private final String type;
private Class<?> idClass;
private static final Logger logger = LoggerFactory.getLogger(MappingElasticsearchEntityInformation.class);
private final ElasticsearchPersistentEntity<T> entityMetadata;
private final String indexName;
private final String type;
private Class<?> idClass;
public MappingElasticsearchEntityInformation(ElasticsearchPersistentEntity<T> entity) {
this(entity, null, null);
}
public MappingElasticsearchEntityInformation(ElasticsearchPersistentEntity<T> entity) {
this(entity, null, null);
}
public MappingElasticsearchEntityInformation(ElasticsearchPersistentEntity<T> entity, String indexName, String type) {
super(entity.getType());
this.entityMetadata = entity;
this.indexName = indexName;
this.type = type;
this.idClass = entity.getIdProperty().getType();
}
public MappingElasticsearchEntityInformation(ElasticsearchPersistentEntity<T> entity, String indexName, String type) {
super(entity.getType());
this.entityMetadata = entity;
this.indexName = indexName;
this.type = type;
this.idClass = entity.getIdProperty().getType();
}
@SuppressWarnings("unchecked")
@Override
public ID getId(T entity) {
ElasticsearchPersistentProperty id = entityMetadata.getIdProperty();
try {
return (ID) BeanWrapper.create(entity, null).getProperty(id);
} catch (Exception e) {
throw new IllegalStateException("ID could not be resolved", e);
}
}
@SuppressWarnings("unchecked")
@Override
public ID getId(T entity) {
ElasticsearchPersistentProperty id = entityMetadata.getIdProperty();
try {
return (ID) BeanWrapper.create(entity, null).getProperty(id);
} catch (Exception e) {
throw new IllegalStateException("ID could not be resolved", e);
}
}
@SuppressWarnings("unchecked")
@Override
public Class<ID> getIdType() {
return (Class<ID>)idClass;
}
@SuppressWarnings("unchecked")
@Override
public Class<ID> getIdType() {
return (Class<ID>) idClass;
}
@Override
public String getIdAttribute() {
Assert.notNull(entityMetadata.getIdProperty(),"Unable to identify 'id' property in class " + entityMetadata.getType().getSimpleName() +". Make sure the 'id' property is annotated with @Id or named as 'id' or 'documentId' ");
return entityMetadata.getIdProperty().getFieldName();
}
@Override
public String getIdAttribute() {
Assert.notNull(entityMetadata.getIdProperty(), "Unable to identify 'id' property in class "
+ entityMetadata.getType().getSimpleName()
+ ". Make sure the 'id' property is annotated with @Id or named as 'id' or 'documentId' ");
return entityMetadata.getIdProperty().getFieldName();
}
@Override
public String getIndexName() {
return indexName != null? indexName : entityMetadata.getIndexName();
}
@Override
public String getIndexName() {
return indexName != null ? indexName : entityMetadata.getIndexName();
}
@Override
public String getType() {
return type != null? type : entityMetadata.getIndexType();
}
@Override
public String getType() {
return type != null ? type : entityMetadata.getIndexType();
}
@Override
public Long getVersion(T entity) {
ElasticsearchPersistentProperty versionProperty = entityMetadata.getVersionProperty();
try {
if(versionProperty != null){
return (Long) BeanWrapper.create(entity, null).getProperty(versionProperty);
}
} catch (Exception e) {
throw new IllegalStateException("failed to load version field", e);
}
return null;
}
@Override
public Long getVersion(T entity) {
ElasticsearchPersistentProperty versionProperty = entityMetadata.getVersionProperty();
try {
if (versionProperty != null) {
return (Long) BeanWrapper.create(entity, null).getProperty(versionProperty);
}
} catch (Exception e) {
throw new IllegalStateException("failed to load version field", e);
}
return null;
}
}

View File

@ -18,34 +18,32 @@ package org.springframework.data.elasticsearch.repository.support;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
/**
* Elasticsearch specific repository implementation. Likely to be used as target within {@link ElasticsearchRepositoryFactory}
* Elasticsearch specific repository implementation. Likely to be used as target within
* {@link ElasticsearchRepositoryFactory}
*
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Ryan Henszey
*/
public class NumberKeyedRepository<T,ID extends Number> extends AbstractElasticsearchRepository<T,ID> {
public class NumberKeyedRepository<T, ID extends Number> extends AbstractElasticsearchRepository<T, ID> {
public NumberKeyedRepository() {
super();
}
public NumberKeyedRepository() {
super();
}
public NumberKeyedRepository(ElasticsearchEntityInformation<T, ID> metadata,
ElasticsearchOperations elasticsearchOperations) {
super(metadata, elasticsearchOperations);
}
public NumberKeyedRepository(ElasticsearchEntityInformation<T, ID> metadata,ElasticsearchOperations elasticsearchOperations) {
super(metadata, elasticsearchOperations);
}
public NumberKeyedRepository(ElasticsearchOperations elasticsearchOperations) {
super(elasticsearchOperations);
}
@Override
protected String stringIdRepresentation(ID id) {
return String.valueOf(id);
}
public NumberKeyedRepository(ElasticsearchOperations elasticsearchOperations) {
super(elasticsearchOperations);
}
@Override
protected String stringIdRepresentation(ID id) {
return String.valueOf(id);
}
}

View File

@ -18,30 +18,32 @@ package org.springframework.data.elasticsearch.repository.support;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
/**
* Elasticsearch specific repository implementation. Likely to be used as target within {@link ElasticsearchRepositoryFactory}
* Elasticsearch specific repository implementation. Likely to be used as target within
* {@link ElasticsearchRepositoryFactory}
*
*
* @author Rizwan Idrees
* @author Mohsin Husen
* @author Ryan Henszey
*/
public class SimpleElasticsearchRepository<T> extends AbstractElasticsearchRepository<T,String> {
public class SimpleElasticsearchRepository<T> extends AbstractElasticsearchRepository<T, String> {
public SimpleElasticsearchRepository() {
super();
}
public SimpleElasticsearchRepository() {
super();
}
public SimpleElasticsearchRepository(ElasticsearchEntityInformation<T, String> metadata,ElasticsearchOperations elasticsearchOperations) {
super(metadata, elasticsearchOperations);
}
public SimpleElasticsearchRepository(ElasticsearchEntityInformation<T, String> metadata,
ElasticsearchOperations elasticsearchOperations) {
super(metadata, elasticsearchOperations);
}
public SimpleElasticsearchRepository(ElasticsearchOperations elasticsearchOperations) {
super(elasticsearchOperations);
}
public SimpleElasticsearchRepository(ElasticsearchOperations elasticsearchOperations) {
super(elasticsearchOperations);
}
@Override
protected String stringIdRepresentation(String id) {
return id;
}
@Override
protected String stringIdRepresentation(String id) {
return id;
}
}

View File

@ -14,28 +14,29 @@
* limitations under the License.
*/
package org.springframework.data.elasticsearch;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class Author {
private String id;
private String name;
private String id;
private String name;
public String getId() {
return id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -17,39 +17,40 @@ package org.springframework.data.elasticsearch;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@Document(indexName = "book",type = "book", indexStoreType = "memory", shards = 1 , replicas = 0, refreshInterval = "-1" )
@Document(indexName = "book", type = "book", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1")
public class Book {
@Id
private String id;
private String name;
private Author author;
@Id
private String id;
private String name;
private Author author;
public String getId() {
return id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public Author getAuthor() {
return author;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
public void setAuthor(Author author) {
this.author = author;
}
}

View File

@ -24,48 +24,46 @@ import org.springframework.data.elasticsearch.annotations.Document;
* @author Mohsin Husen
*/
@Document(indexName = "double-keyed-entity", type = "double-keyed-entity", indexStoreType = "memory", shards = 1 , replicas = 0, refreshInterval = "-1")
@Document(indexName = "double-keyed-entity", type = "double-keyed-entity", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1")
public class DoubleIDEntity {
@Id
private Double id;
private String type;
private String message;
@Version
private Long version;
@Id
private Double id;
private String type;
private String message;
@Version
private Long version;
public Double getId() {
return id;
}
public Double getId() {
return id;
}
public void setId(Double id) {
this.id = id;
}
public void setId(Double id) {
this.id = id;
}
public String getType() {
return type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void setType(String type) {
this.type = type;
}
public String getMessage() {
return message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public void setMessage(String message) {
this.message = message;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
}

View File

@ -24,49 +24,46 @@ import org.springframework.data.elasticsearch.annotations.Document;
* @author Mohsin Husen
*/
@Document(indexName = "integer-keyed-entity", type = "integer-keyed-entity", indexStoreType = "memory", shards = 1 , replicas = 0, refreshInterval = "-1")
@Document(indexName = "integer-keyed-entity", type = "integer-keyed-entity", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1")
public class IntegerIDEntity {
@Id
private Integer id;
private String type;
private String message;
@Version
private Long version;
@Id
private Integer id;
private String type;
private String message;
@Version
private Long version;
public Integer getId() {
return id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setId(Integer id) {
this.id = id;
}
public String getType() {
return type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void setType(String type) {
this.type = type;
}
public String getMessage() {
return message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public void setMessage(String message) {
this.message = message;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
}

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.data.elasticsearch.repositories.SampleElasticSearchBookRepository;
@ -24,38 +23,36 @@ import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
import static org.apache.commons.lang.RandomStringUtils.randomAlphanumeric;
import static org.hamcrest.Matchers.is;
import static org.hamcrest.Matchers.notNullValue;
import static org.junit.Assert.assertThat;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/repository-test-nested-object.xml")
public class NestedObjectTests{
public class NestedObjectTests {
@Resource
private SampleElasticSearchBookRepository repository;
@Resource
private SampleElasticSearchBookRepository repository;
@Test
public void shouldIndexNestedObject(){
//given
String id = randomAlphanumeric(5);
Book book = new Book();
book.setId(id);
book.setName("xyz");
Author author = new Author();
author.setId("1");
author.setName("ABC");
book.setAuthor(author);
//when
repository.save(book);
//then
assertThat(repository.findOne(id), is(notNullValue()));
}
@Test
public void shouldIndexNestedObject() {
// given
String id = randomAlphanumeric(5);
Book book = new Book();
book.setId(id);
book.setName("xyz");
Author author = new Author();
author.setId("1");
author.setName("ABC");
book.setAuthor(author);
// when
repository.save(book);
// then
assertThat(repository.findOne(id), is(notNullValue()));
}
}

View File

@ -15,32 +15,32 @@
*/
package org.springframework.data.elasticsearch;
import org.springframework.data.annotation.Id;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class NonDocumentEntity {
@Id
private String someId;
private String someField1;
private String someField2;
@Id
private String someId;
private String someField1;
private String someField2;
public String getSomeField1() {
return someField1;
}
public String getSomeField1() {
return someField1;
}
public void setSomeField1(String someField1) {
this.someField1 = someField1;
}
public void setSomeField1(String someField1) {
this.someField1 = someField1;
}
public String getSomeField2() {
return someField2;
}
public String getSomeField2() {
return someField2;
}
public void setSomeField2(String someField2) {
this.someField2 = someField2;
}
public void setSomeField2(String someField2) {
this.someField2 = someField2;
}
}

View File

@ -15,23 +15,21 @@
*/
package org.springframework.data.elasticsearch;
import org.junit.Test;
import org.springframework.beans.factory.BeanCreationException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.data.elasticsearch.repositories.NonDocumentEntityRepository;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class NonDocumentEntityTests {
@Test(expected = BeanCreationException.class)
public void shouldNotInitialiseRepositoryWithNonDocument(){
//when
ClassPathXmlApplicationContext ctx =
new ClassPathXmlApplicationContext("/repository-non-document-entity.xml");
ctx.getBean(NonDocumentEntityRepository.class);
}
@Test(expected = BeanCreationException.class)
public void shouldNotInitialiseRepositoryWithNonDocument() {
// when
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("/repository-non-document-entity.xml");
ctx.getBean(NonDocumentEntityRepository.class);
}
}

View File

@ -25,93 +25,82 @@ import org.springframework.data.elasticsearch.annotations.Document;
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@Document(indexName = "test-index", type = "test-type", indexStoreType = "memory", shards = 1 , replicas = 0, refreshInterval = "-1")
@Document(indexName = "test-index", type = "test-type", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1")
public class SampleEntity {
@Id
private String id;
private String type;
private String message;
private int rate;
private boolean available;
@Version
private Long version;
@Id
private String id;
private String type;
private String message;
private int rate;
private boolean available;
@Version
private Long version;
public String getId() {
return id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public void setType(String type) {
this.type = type;
}
public String getMessage() {
return message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void setMessage(String message) {
this.message = message;
}
public int getRate() {
return rate;
}
public int getRate() {
return rate;
}
public void setRate(int rate) {
this.rate = rate;
}
public void setRate(int rate) {
this.rate = rate;
}
public boolean isAvailable() {
return available;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
public void setAvailable(boolean available) {
this.available = available;
}
public Long getVersion() {
return version;
}
public Long getVersion() {
return version;
}
public void setVersion(Long version) {
this.version = version;
}
public void setVersion(Long version) {
this.version = version;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SampleEntity)) {
return false;
}
if (this == obj) {
return true;
}
SampleEntity rhs = (SampleEntity) obj;
return new EqualsBuilder().append(this.id, rhs.id)
.append(this.type, rhs.type)
.append(this.message, rhs.message)
.append(this.rate,rhs.rate)
.append(this.available,rhs.available)
.append(this.version,rhs.version)
.isEquals();
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof SampleEntity)) {
return false;
}
if (this == obj) {
return true;
}
SampleEntity rhs = (SampleEntity) obj;
return new EqualsBuilder().append(this.id, rhs.id).append(this.type, rhs.type).append(this.message, rhs.message)
.append(this.rate, rhs.rate).append(this.available, rhs.available).append(this.version, rhs.version).isEquals();
}
@Override
public int hashCode() {
return new HashCodeBuilder()
.append(id)
.append(type)
.append(message)
.append(rate)
.append(available)
.append(version)
.toHashCode();
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(id).append(type).append(message).append(rate).append(available).append(version)
.toHashCode();
}
}

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch;
import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field;
@ -24,47 +23,43 @@ import org.springframework.data.elasticsearch.annotations.Field;
* @author Rizwan Idrees
* @author Mohsin Husen
*/
@Document(indexName = "test-mapping", type = "mapping", indexStoreType = "memory", shards = 1 , replicas = 0, refreshInterval = "-1")
@Document(indexName = "test-mapping", type = "mapping", indexStoreType = "memory", shards = 1, replicas = 0, refreshInterval = "-1")
public class SampleMappingEntity {
@Id
private String id;
@Field(type = "string", index = "not_analyzed", store = true, searchAnalyzer = "standard", indexAnalyzer = "standard")
private String message;
@Id
private String id;
@Field(type = "string", index = "not_analyzed", store = true, searchAnalyzer = "standard", indexAnalyzer = "standard")
private String message;
private NestedEntity nested;
private NestedEntity nested;
public String getId() {
return id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setId(String id) {
this.id = id;
}
public String getMessage() {
return message;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public void setMessage(String message) {
this.message = message;
}
static class NestedEntity {
@Field(type = "string")
private String someField;
static class NestedEntity{
@Field(type = "string")
private String someField;
public String getSomeField() {
return someField;
}
public String getSomeField() {
return someField;
}
public void setSomeField(String someField) {
this.someField = someField;
}
}
public void setSomeField(String someField) {
this.someField = someField;
}
}
}

View File

@ -39,25 +39,26 @@ import static org.junit.Assert.assertThat;
@ContextConfiguration("namespace.xml")
public class ElasticsearchNamespaceHandlerTests {
@Autowired
private ApplicationContext context;
@Autowired
private ApplicationContext context;
@Test
public void shouldCreatesNodeClient() {
assertThat(context.getBean(NodeClientFactoryBean.class), is(notNullValue()));
assertThat(context.getBean(NodeClientFactoryBean.class), is(instanceOf(NodeClientFactoryBean.class)));
}
@Test
public void shouldCreatesNodeClient() {
assertThat(context.getBean(NodeClientFactoryBean.class), is(notNullValue()));
assertThat(context.getBean(NodeClientFactoryBean.class), is(instanceOf(NodeClientFactoryBean.class)));
}
@Test
public void shouldCreateTransportClient() {
assertThat(context.getBean(TransportClientFactoryBean.class), is(notNullValue()));
assertThat(context.getBean(TransportClientFactoryBean.class), is(instanceOf(TransportClientFactoryBean.class)));
}
@Test
public void shouldCreateTransportClient() {
assertThat(context.getBean(TransportClientFactoryBean.class), is(notNullValue()));
assertThat(context.getBean(TransportClientFactoryBean.class), is(instanceOf(TransportClientFactoryBean.class)));
}
@Test
public void shouldCreateRepository(){
assertThat(context.getBean(TransportClientFactoryBean.class), is(notNullValue()));
assertThat(context.getBean(SampleElasticsearchRepository.class), is(instanceOf(SampleElasticsearchRepository.class)));
}
@Test
public void shouldCreateRepository() {
assertThat(context.getBean(TransportClientFactoryBean.class), is(notNullValue()));
assertThat(context.getBean(SampleElasticsearchRepository.class),
is(instanceOf(SampleElasticsearchRepository.class)));
}
}

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch.config;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
@ -41,22 +40,22 @@ import static org.junit.Assert.assertThat;
@ContextConfiguration
public class EnableElasticsearchRepositoriesTests {
@Configuration
@EnableElasticsearchRepositories(basePackages = "org.springframework.data.elasticsearch.repositories")
static class Config {
@Configuration
@EnableElasticsearchRepositories(basePackages = "org.springframework.data.elasticsearch.repositories")
static class Config {
@Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchTemplate(nodeBuilder().local(true).clusterName("testCluster").node().client());
}
}
@Bean
public ElasticsearchOperations elasticsearchTemplate() {
return new ElasticsearchTemplate(nodeBuilder().local(true).clusterName("testCluster").node().client());
}
}
@Autowired
private SampleElasticsearchRepository repository;
@Autowired
private SampleElasticsearchRepository repository;
@Test
public void bootstrapsRepository() {
assertThat(repository, is(notNullValue()));
}
@Test
public void bootstrapsRepository() {
assertThat(repository, is(notNullValue()));
}
}

View File

@ -31,44 +31,44 @@ import java.util.TimeZone;
* @author Mohsin Husen
*/
public class DateTimeConvertersTests {
@Test
public void testJodaDateTimeConverterWithNullValue() {
Assert.assertNull(DateTimeConverters.JodaDateTimeConverter.INSTANCE.convert(null));
}
@Test
public void testJodaDateTimeConverterWithNullValue() {
Assert.assertNull(DateTimeConverters.JodaDateTimeConverter.INSTANCE.convert(null));
}
@Test
public void testJodaDateTimeConverter() {
DateTime dateTime = new DateTime(2013, 1,24 , 6, 35, 0, DateTimeZone.UTC);
Assert.assertEquals("2013-01-24T06:35:00.000Z",
DateTimeConverters.JodaDateTimeConverter.INSTANCE.convert(dateTime));
}
@Test
public void testJodaDateTimeConverter() {
DateTime dateTime = new DateTime(2013, 1, 24, 6, 35, 0, DateTimeZone.UTC);
Assert
.assertEquals("2013-01-24T06:35:00.000Z", DateTimeConverters.JodaDateTimeConverter.INSTANCE.convert(dateTime));
}
@Test
public void testJodaLocalDateTimeConverterWithNullValue() {
Assert.assertNull(DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE.convert(null));
}
@Test
public void testJodaLocalDateTimeConverterWithNullValue() {
Assert.assertNull(DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE.convert(null));
}
@Test
public void testJodaLocalDateTimeConverter() {
LocalDateTime dateTime = new LocalDateTime(new DateTime(2013, 1,24, 6, 35, 0, DateTimeZone.UTC).getMillis(),
DateTimeZone.UTC);
Assert.assertEquals("2013-01-24T06:35:00.000Z",
DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE.convert(dateTime));
}
@Test
public void testJodaLocalDateTimeConverter() {
LocalDateTime dateTime = new LocalDateTime(new DateTime(2013, 1, 24, 6, 35, 0, DateTimeZone.UTC).getMillis(),
DateTimeZone.UTC);
Assert.assertEquals("2013-01-24T06:35:00.000Z",
DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE.convert(dateTime));
}
@Test
public void testJavaDateConverterWithNullValue() {
Assert.assertNull(DateTimeConverters.JavaDateConverter.INSTANCE.convert(null));
}
@Test
public void testJavaDateConverterWithNullValue() {
Assert.assertNull(DateTimeConverters.JavaDateConverter.INSTANCE.convert(null));
}
@Test
public void testJavaDateConverter() {
DateTime dateTime = new DateTime(2013, 1,24, 6, 35, 0, DateTimeZone.UTC);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTimeInMillis(dateTime.getMillis());
@Test
public void testJavaDateConverter() {
DateTime dateTime = new DateTime(2013, 1, 24, 6, 35, 0, DateTimeZone.UTC);
Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTimeInMillis(dateTime.getMillis());
Assert.assertEquals("2013-01-24T06:35:00.000Z",
DateTimeConverters.JavaDateConverter.INSTANCE.convert(calendar.getTime()));
}
Assert.assertEquals("2013-01-24T06:35:00.000Z",
DateTimeConverters.JavaDateConverter.INSTANCE.convert(calendar.getTime()));
}
}

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch.core.convert;
import org.junit.Test;
import org.springframework.core.convert.ConversionService;
import org.springframework.data.elasticsearch.core.mapping.SimpleElasticsearchMappingContext;
@ -23,36 +22,37 @@ import org.springframework.data.mapping.context.MappingContext;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class MappingElasticsearchConverterTests {
@Test(expected = IllegalArgumentException.class)
public void shouldFailToInitializeGivenMappingContextIsNull(){
//given
new MappingElasticsearchConverter(null);
}
@Test(expected = IllegalArgumentException.class)
public void shouldFailToInitializeGivenMappingContextIsNull() {
// given
new MappingElasticsearchConverter(null);
}
@Test
public void shouldReturnMappingContextWithWhichItWasInitialized(){
//given
MappingContext mappingContext = new SimpleElasticsearchMappingContext();
MappingElasticsearchConverter converter = new MappingElasticsearchConverter(mappingContext);
//then
assertThat(converter.getMappingContext(), is(notNullValue()));
assertThat(converter.getMappingContext(), is(sameInstance(mappingContext)));
}
@Test
public void shouldReturnMappingContextWithWhichItWasInitialized() {
// given
MappingContext mappingContext = new SimpleElasticsearchMappingContext();
MappingElasticsearchConverter converter = new MappingElasticsearchConverter(mappingContext);
// then
assertThat(converter.getMappingContext(), is(notNullValue()));
assertThat(converter.getMappingContext(), is(sameInstance(mappingContext)));
}
@Test
public void shouldReturnDefaultConversionService(){
//given
MappingElasticsearchConverter converter = new MappingElasticsearchConverter(new SimpleElasticsearchMappingContext());
//when
ConversionService conversionService = converter.getConversionService();
//then
assertThat(conversionService, is(notNullValue()));
}
@Test
public void shouldReturnDefaultConversionService() {
// given
MappingElasticsearchConverter converter = new MappingElasticsearchConverter(new SimpleElasticsearchMappingContext());
// when
ConversionService conversionService = converter.getConversionService();
// then
assertThat(conversionService, is(notNullValue()));
}
}

View File

@ -24,85 +24,85 @@ import org.springframework.data.util.TypeInformation;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public class SimpleElasticsearchPersistentEntityTests {
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionGivenVersionPropertyIsNotLong() throws NoSuchFieldException, IntrospectionException {
//given
TypeInformation typeInformation = ClassTypeInformation.from(EntityWithWrongVersionType.class);
SimpleElasticsearchPersistentProperty persistentProperty =
new SimpleElasticsearchPersistentProperty(EntityWithWrongVersionType.class.getDeclaredField("version"),
new PropertyDescriptor("version", EntityWithWrongVersionType.class),
new SimpleElasticsearchPersistentEntity<EntityWithWrongVersionType>(typeInformation),
new SimpleTypeHolder());
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionGivenVersionPropertyIsNotLong() throws NoSuchFieldException, IntrospectionException {
// given
TypeInformation typeInformation = ClassTypeInformation.from(EntityWithWrongVersionType.class);
SimpleElasticsearchPersistentProperty persistentProperty = new SimpleElasticsearchPersistentProperty(
EntityWithWrongVersionType.class.getDeclaredField("version"), new PropertyDescriptor("version",
EntityWithWrongVersionType.class), new SimpleElasticsearchPersistentEntity<EntityWithWrongVersionType>(
typeInformation), new SimpleTypeHolder());
//when
new SimpleElasticsearchPersistentEntity(typeInformation).addPersistentProperty(persistentProperty);
}
// when
new SimpleElasticsearchPersistentEntity(typeInformation).addPersistentProperty(persistentProperty);
}
@Test(expected = MappingException.class)
public void shouldThrowExceptionGivenMultipleVersionPropertiesArePresent() throws NoSuchFieldException,
IntrospectionException {
// given
TypeInformation typeInformation = ClassTypeInformation.from(EntityWithMultipleVersionField.class);
SimpleElasticsearchPersistentProperty persistentProperty1 = new SimpleElasticsearchPersistentProperty(
EntityWithMultipleVersionField.class.getDeclaredField("version1"), new PropertyDescriptor("version1",
EntityWithMultipleVersionField.class),
new SimpleElasticsearchPersistentEntity<EntityWithMultipleVersionField>(typeInformation),
new SimpleTypeHolder());
@Test(expected = MappingException.class)
public void shouldThrowExceptionGivenMultipleVersionPropertiesArePresent() throws NoSuchFieldException, IntrospectionException {
//given
TypeInformation typeInformation = ClassTypeInformation.from(EntityWithMultipleVersionField.class);
SimpleElasticsearchPersistentProperty persistentProperty1 =
new SimpleElasticsearchPersistentProperty(EntityWithMultipleVersionField.class.getDeclaredField("version1"),
new PropertyDescriptor("version1", EntityWithMultipleVersionField.class),
new SimpleElasticsearchPersistentEntity<EntityWithMultipleVersionField>(typeInformation),
new SimpleTypeHolder());
SimpleElasticsearchPersistentProperty persistentProperty2 = new SimpleElasticsearchPersistentProperty(
EntityWithMultipleVersionField.class.getDeclaredField("version2"), new PropertyDescriptor("version2",
EntityWithMultipleVersionField.class),
new SimpleElasticsearchPersistentEntity<EntityWithMultipleVersionField>(typeInformation),
new SimpleTypeHolder());
SimpleElasticsearchPersistentProperty persistentProperty2 =
new SimpleElasticsearchPersistentProperty(EntityWithMultipleVersionField.class.getDeclaredField("version2"),
new PropertyDescriptor("version2", EntityWithMultipleVersionField.class),
new SimpleElasticsearchPersistentEntity<EntityWithMultipleVersionField>(typeInformation),
new SimpleTypeHolder());
SimpleElasticsearchPersistentEntity simpleElasticsearchPersistentEntity = new SimpleElasticsearchPersistentEntity(
typeInformation);
simpleElasticsearchPersistentEntity.addPersistentProperty(persistentProperty1);
// when
simpleElasticsearchPersistentEntity.addPersistentProperty(persistentProperty2);
}
SimpleElasticsearchPersistentEntity simpleElasticsearchPersistentEntity = new SimpleElasticsearchPersistentEntity(typeInformation);
simpleElasticsearchPersistentEntity.addPersistentProperty(persistentProperty1);
//when
simpleElasticsearchPersistentEntity.addPersistentProperty(persistentProperty2);
}
private class EntityWithWrongVersionType {
@Version
private String version;
public String getVersion() {
return version;
}
private class EntityWithWrongVersionType {
@Version
private String version;
public void setVersion(String version) {
this.version = version;
}
}
public String getVersion() {
return version;
}
private class EntityWithMultipleVersionField {
public void setVersion(String version) {
this.version = version;
}
}
@Version
private Long version1;
@Version
private Long version2;
private class EntityWithMultipleVersionField{
public Long getVersion1() {
return version1;
}
@Version
private Long version1;
@Version
private Long version2;
public void setVersion1(Long version1) {
this.version1 = version1;
}
public Long getVersion1() {
return version1;
}
public Long getVersion2() {
return version2;
}
public void setVersion1(Long version1) {
this.version1 = version1;
}
public Long getVersion2() {
return version2;
}
public void setVersion2(Long version2) {
this.version2 = version2;
}
}
public void setVersion2(Long version2) {
this.version2 = version2;
}
}
}

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch.repositories;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -38,6 +37,7 @@ import static org.apache.commons.lang.RandomStringUtils.randomNumeric;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
@ -46,454 +46,450 @@ import static org.junit.Assert.assertThat;
@ContextConfiguration("classpath:custom-method-repository-test.xml")
public class CustomMethodRepositoryTests {
@Resource
private SampleCustomMethodRepository repository;
@Resource
private SampleCustomMethodRepository repository;
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Autowired
private ElasticsearchTemplate elasticsearchTemplate;
@Before
public void before(){
elasticsearchTemplate.createIndex(SampleEntity.class);
DeleteQuery deleteQuery = new DeleteQuery();
deleteQuery.setQuery(matchAllQuery());
elasticsearchTemplate.delete(deleteQuery,SampleEntity.class);
elasticsearchTemplate.refresh(SampleEntity.class, true);
}
@Before
public void before() {
elasticsearchTemplate.createIndex(SampleEntity.class);
DeleteQuery deleteQuery = new DeleteQuery();
deleteQuery.setQuery(matchAllQuery());
elasticsearchTemplate.delete(deleteQuery, SampleEntity.class);
elasticsearchTemplate.refresh(SampleEntity.class, true);
}
@Test
public void shouldExecuteCustomMethod(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setMessage("some message");
repository.save(sampleEntity);
//when
Page<SampleEntity> page = repository.findByType("test", new PageRequest(0, 10));
//then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
}
@Test
public void shouldExecuteCustomMethod() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setMessage("some message");
repository.save(sampleEntity);
// when
Page<SampleEntity> page = repository.findByType("test", new PageRequest(0, 10));
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
}
@Test
public void shouldExecuteCustomMethodForNot(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("some");
sampleEntity.setMessage("some message");
repository.save(sampleEntity);
//when
Page<SampleEntity> page = repository.findByTypeNot("test", new PageRequest(0, 10));
//then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
@Test
public void shouldExecuteCustomMethodForNot() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("some");
sampleEntity.setMessage("some message");
repository.save(sampleEntity);
// when
Page<SampleEntity> page = repository.findByTypeNot("test", new PageRequest(0, 10));
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
@Test
public void shouldExecuteCustomMethodWithQuery(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setMessage("customQuery");
repository.save(sampleEntity);
//when
Page<SampleEntity> page = repository.findByMessage("customQuery", new PageRequest(0, 10));
//then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
}
@Test
public void shouldExecuteCustomMethodWithQuery() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setMessage("customQuery");
repository.save(sampleEntity);
// when
Page<SampleEntity> page = repository.findByMessage("customQuery", new PageRequest(0, 10));
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
}
@Test
public void shouldExecuteCustomMethodWithLessThan() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setRate(10);
sampleEntity.setMessage("some message");
repository.save(sampleEntity);
@Test
public void shouldExecuteCustomMethodWithLessThan(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setRate(10);
sampleEntity.setMessage("some message");
repository.save(sampleEntity);
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setType("test");
sampleEntity2.setRate(20);
sampleEntity2.setMessage("some message");
repository.save(sampleEntity2);
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setType("test");
sampleEntity2.setRate(20);
sampleEntity2.setMessage("some message");
repository.save(sampleEntity2);
// when
Page<SampleEntity> page = repository.findByRateLessThan(10, new PageRequest(0, 10));
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
//when
Page<SampleEntity> page = repository.findByRateLessThan(10, new PageRequest(0, 10));
//then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
@Test
public void shouldExecuteCustomMethodWithBefore() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setRate(10);
sampleEntity.setMessage("some message");
repository.save(sampleEntity);
@Test
public void shouldExecuteCustomMethodWithBefore(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setRate(10);
sampleEntity.setMessage("some message");
repository.save(sampleEntity);
// when
Page<SampleEntity> page = repository.findByRateBefore(10, new PageRequest(0, 10));
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
//when
Page<SampleEntity> page = repository.findByRateBefore(10, new PageRequest(0, 10));
//then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
@Test
public void shouldExecuteCustomMethodWithAfter() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setRate(10);
sampleEntity.setMessage("some message");
repository.save(sampleEntity);
@Test
public void shouldExecuteCustomMethodWithAfter(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setRate(10);
sampleEntity.setMessage("some message");
repository.save(sampleEntity);
// when
Page<SampleEntity> page = repository.findByRateAfter(10, new PageRequest(0, 10));
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
//when
Page<SampleEntity> page = repository.findByRateAfter(10, new PageRequest(0, 10));
//then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
@Test
public void shouldExecuteCustomMethodWithLike() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setRate(10);
sampleEntity.setMessage("foo");
repository.save(sampleEntity);
@Test
public void shouldExecuteCustomMethodWithLike(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setRate(10);
sampleEntity.setMessage("foo");
repository.save(sampleEntity);
// when
Page<SampleEntity> page = repository.findByMessageLike("fo", new PageRequest(0, 10));
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
//when
Page<SampleEntity> page = repository.findByMessageLike("fo", new PageRequest(0, 10));
//then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
@Test
public void shouldExecuteCustomMethodForStartingWith() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setRate(10);
sampleEntity.setMessage("foo");
repository.save(sampleEntity);
@Test
public void shouldExecuteCustomMethodForStartingWith(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setRate(10);
sampleEntity.setMessage("foo");
repository.save(sampleEntity);
// when
Page<SampleEntity> page = repository.findByMessageStartingWith("fo", new PageRequest(0, 10));
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
//when
Page<SampleEntity> page = repository.findByMessageStartingWith("fo", new PageRequest(0, 10));
//then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
@Test
public void shouldExecuteCustomMethodForEndingWith() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setRate(10);
sampleEntity.setMessage("foo");
repository.save(sampleEntity);
@Test
public void shouldExecuteCustomMethodForEndingWith(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setRate(10);
sampleEntity.setMessage("foo");
repository.save(sampleEntity);
// when
Page<SampleEntity> page = repository.findByMessageEndingWith("o", new PageRequest(0, 10));
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
//when
Page<SampleEntity> page = repository.findByMessageEndingWith("o", new PageRequest(0, 10));
//then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
@Test
public void shouldExecuteCustomMethodForContains() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setRate(10);
sampleEntity.setMessage("foo");
repository.save(sampleEntity);
@Test
public void shouldExecuteCustomMethodForContains(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setRate(10);
sampleEntity.setMessage("foo");
repository.save(sampleEntity);
// when
Page<SampleEntity> page = repository.findByMessageContaining("fo", new PageRequest(0, 10));
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
//when
Page<SampleEntity> page = repository.findByMessageContaining("fo", new PageRequest(0, 10));
//then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
@Test
public void shouldExecuteCustomMethodForIn() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setMessage("foo");
repository.save(sampleEntity);
@Test
public void shouldExecuteCustomMethodForIn(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setMessage("foo");
repository.save(sampleEntity);
// given
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setType("test");
sampleEntity2.setMessage("bar");
repository.save(sampleEntity2);
//given
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setType("test");
sampleEntity2.setMessage("bar");
repository.save(sampleEntity2);
List<String> ids = Arrays.asList(documentId, documentId2);
List<String> ids = Arrays.asList(documentId,documentId2);
// when
Page<SampleEntity> page = repository.findByIdIn(ids, new PageRequest(0, 10));
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(2L)));
}
//when
Page<SampleEntity> page = repository.findByIdIn(ids, new PageRequest(0, 10));
//then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(2L)));
}
@Test
public void shouldExecuteCustomMethodForNotIn() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setMessage("foo");
repository.save(sampleEntity);
@Test
public void shouldExecuteCustomMethodForNotIn(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setMessage("foo");
repository.save(sampleEntity);
// given
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setType("test");
sampleEntity2.setMessage("bar");
repository.save(sampleEntity2);
//given
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setType("test");
sampleEntity2.setMessage("bar");
repository.save(sampleEntity2);
List<String> ids = Arrays.asList(documentId);
List<String> ids = Arrays.asList(documentId);
// when
Page<SampleEntity> page = repository.findByIdNotIn(ids, new PageRequest(0, 10));
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
assertThat(page.getContent().get(0).getId(), is(documentId2));
}
//when
Page<SampleEntity> page = repository.findByIdNotIn(ids, new PageRequest(0, 10));
//then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
assertThat(page.getContent().get(0).getId(),is(documentId2));
}
@Test
public void shouldExecuteCustomMethodForTrue() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setMessage("foo");
sampleEntity.setAvailable(true);
repository.save(sampleEntity);
@Test
public void shouldExecuteCustomMethodForTrue(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setMessage("foo");
sampleEntity.setAvailable(true);
repository.save(sampleEntity);
// given
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setType("test");
sampleEntity2.setMessage("bar");
sampleEntity2.setAvailable(false);
repository.save(sampleEntity2);
// when
Page<SampleEntity> page = repository.findByAvailableTrue(new PageRequest(0, 10));
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
//given
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setType("test");
sampleEntity2.setMessage("bar");
sampleEntity2.setAvailable(false);
repository.save(sampleEntity2);
//when
Page<SampleEntity> page = repository.findByAvailableTrue(new PageRequest(0, 10));
//then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
@Test
public void shouldExecuteCustomMethodForFalse() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setMessage("foo");
sampleEntity.setAvailable(true);
repository.save(sampleEntity);
@Test
public void shouldExecuteCustomMethodForFalse(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setMessage("foo");
sampleEntity.setAvailable(true);
repository.save(sampleEntity);
// given
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setType("test");
sampleEntity2.setMessage("bar");
sampleEntity2.setAvailable(false);
repository.save(sampleEntity2);
// when
Page<SampleEntity> page = repository.findByAvailableFalse(new PageRequest(0, 10));
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
//given
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setType("test");
sampleEntity2.setMessage("bar");
sampleEntity2.setAvailable(false);
repository.save(sampleEntity2);
//when
Page<SampleEntity> page = repository.findByAvailableFalse(new PageRequest(0, 10));
//then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
@Test
public void shouldExecuteCustomMethodForOrderBy() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("abc");
sampleEntity.setMessage("test");
sampleEntity.setAvailable(true);
repository.save(sampleEntity);
@Test
public void shouldExecuteCustomMethodForOrderBy(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("abc");
sampleEntity.setMessage("test");
sampleEntity.setAvailable(true);
repository.save(sampleEntity);
// document 2
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setType("xyz");
sampleEntity2.setMessage("bar");
sampleEntity2.setAvailable(false);
repository.save(sampleEntity2);
//document 2
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setType("xyz");
sampleEntity2.setMessage("bar");
sampleEntity2.setAvailable(false);
repository.save(sampleEntity2);
// document 3
String documentId3 = randomNumeric(5);
SampleEntity sampleEntity3 = new SampleEntity();
sampleEntity3.setId(documentId3);
sampleEntity3.setType("def");
sampleEntity3.setMessage("foo");
sampleEntity3.setAvailable(false);
repository.save(sampleEntity3);
//document 3
String documentId3 = randomNumeric(5);
SampleEntity sampleEntity3 = new SampleEntity();
sampleEntity3.setId(documentId3);
sampleEntity3.setType("def");
sampleEntity3.setMessage("foo");
sampleEntity3.setAvailable(false);
repository.save(sampleEntity3);
// when
Page<SampleEntity> page = repository.findByMessageOrderByTypeAsc("foo", new PageRequest(0, 10));
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
//when
Page<SampleEntity> page = repository.findByMessageOrderByTypeAsc("foo",new PageRequest(0, 10));
//then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
@Test
public void shouldExecuteCustomMethodWithBooleanParameter() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setMessage("foo");
sampleEntity.setAvailable(true);
repository.save(sampleEntity);
@Test
public void shouldExecuteCustomMethodWithBooleanParameter(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setType("test");
sampleEntity.setMessage("foo");
sampleEntity.setAvailable(true);
repository.save(sampleEntity);
// given
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setType("test");
sampleEntity2.setMessage("bar");
sampleEntity2.setAvailable(false);
repository.save(sampleEntity2);
// when
Page<SampleEntity> page = repository.findByAvailable(false, new PageRequest(0, 10));
// then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
//given
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setType("test");
sampleEntity2.setMessage("bar");
sampleEntity2.setAvailable(false);
repository.save(sampleEntity2);
//when
Page<SampleEntity> page = repository.findByAvailable(false, new PageRequest(0, 10));
//then
assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L)));
}
@Test
public void shouldReturnPageableResultsWithQueryAnnotationExpectedPageSize() {
// given
for (int i = 0; i < 30; i++) {
String documentId = String.valueOf(i);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("message");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
}
// when
Page<SampleEntity> pageResult = repository.findByMessage("message", new PageRequest(0, 23, new Sort(new Sort.Order(
Sort.Direction.ASC, "message"))));
// then
assertThat(pageResult.getTotalElements(), is(equalTo(30L)));
assertThat(pageResult.getContent().size(), is(equalTo(23)));
}
@Test
public void shouldReturnPageableResultsWithQueryAnnotationExpectedPageSize() {
// given
for (int i = 0; i < 30; i++) {
String documentId = String.valueOf(i);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("message");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
}
// when
Page<SampleEntity> pageResult = repository.findByMessage("message", new PageRequest(0, 23, new Sort(new Sort.Order(Sort.Direction.ASC,"message"))));
// then
assertThat(pageResult.getTotalElements(), is(equalTo(30L)));
assertThat(pageResult.getContent().size(), is(equalTo(23)));
}
@Test
public void shouldReturnPageableResultsWithGivenSortingOrder() {
// given
String documentId = random(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("abc");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
@Test
public void shouldReturnPageableResultsWithGivenSortingOrder(){
//given
String documentId = random(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("abc");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("abd");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity2);
String documentId3 = randomNumeric(5);
SampleEntity sampleEntity3 = new SampleEntity();
sampleEntity3.setId(documentId3);
sampleEntity3.setMessage("abe");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity3);
//when
Page<SampleEntity> pageResult = repository.findByMessageContaining("a", new PageRequest(0, 23, new Sort(new Sort.Order(Sort.Direction.DESC,"message"))));
//then
assertThat(pageResult.getContent().isEmpty(),is(false));
assertThat(pageResult.getContent().get(0).getMessage(),is(sampleEntity3.getMessage()));
}
@Test
public void shouldReturnListForMessage(){
//given
String documentId = random(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("abc");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("abd");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity2);
String documentId3 = randomNumeric(5);
SampleEntity sampleEntity3 = new SampleEntity();
sampleEntity3.setId(documentId3);
sampleEntity3.setMessage("abe");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity3);
//when
List<SampleEntity> sampleEntities = repository.findByMessage("abc");
//then
assertThat(sampleEntities.isEmpty(),is(false));
assertThat(sampleEntities.size(),is(1));
}
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("abd");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity2);
String documentId3 = randomNumeric(5);
SampleEntity sampleEntity3 = new SampleEntity();
sampleEntity3.setId(documentId3);
sampleEntity3.setMessage("abe");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity3);
// when
Page<SampleEntity> pageResult = repository.findByMessageContaining("a", new PageRequest(0, 23, new Sort(
new Sort.Order(Sort.Direction.DESC, "message"))));
// then
assertThat(pageResult.getContent().isEmpty(), is(false));
assertThat(pageResult.getContent().get(0).getMessage(), is(sampleEntity3.getMessage()));
}
@Test
public void shouldReturnListForMessage() {
// given
String documentId = random(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("abc");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("abd");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity2);
String documentId3 = randomNumeric(5);
SampleEntity sampleEntity3 = new SampleEntity();
sampleEntity3.setId(documentId3);
sampleEntity3.setMessage("abe");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity3);
// when
List<SampleEntity> sampleEntities = repository.findByMessage("abc");
// then
assertThat(sampleEntities.isEmpty(), is(false));
assertThat(sampleEntities.size(), is(1));
}
}

View File

@ -18,8 +18,6 @@ package org.springframework.data.elasticsearch.repositories;
import org.springframework.data.elasticsearch.DoubleIDEntity;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface DoubleIDRepository extends ElasticsearchRepository<DoubleIDEntity,Double> {
public interface DoubleIDRepository extends ElasticsearchRepository<DoubleIDEntity, Double> {
}

View File

@ -18,6 +18,6 @@ package org.springframework.data.elasticsearch.repositories;
import org.springframework.data.elasticsearch.IntegerIDEntity;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
public interface IntegerIDRepository extends ElasticsearchRepository<IntegerIDEntity,Integer> {
public interface IntegerIDRepository extends ElasticsearchRepository<IntegerIDEntity, Integer> {
}

View File

@ -22,5 +22,5 @@ import org.springframework.data.elasticsearch.repository.ElasticsearchRepository
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public interface NonDocumentEntityRepository extends ElasticsearchRepository<NonDocumentEntity,String> {
public interface NonDocumentEntityRepository extends ElasticsearchRepository<NonDocumentEntity, String> {
}

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch.repositories;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.SampleEntity;
@ -23,46 +22,47 @@ import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import java.util.List;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public interface SampleCustomMethodRepository extends ElasticsearchRepository<SampleEntity,String> {
public interface SampleCustomMethodRepository extends ElasticsearchRepository<SampleEntity, String> {
Page<SampleEntity> findByType(String type, Pageable pageable);
Page<SampleEntity> findByType(String type, Pageable pageable);
Page<SampleEntity> findByTypeNot(String type, Pageable pageable);
Page<SampleEntity> findByTypeNot(String type, Pageable pageable);
@Query("{\"bool\" : {\"must\" : {\"field\" : {\"message\" : \"?0\"}}}}")
Page<SampleEntity> findByMessage(String message, Pageable pageable);
@Query("{\"bool\" : {\"must\" : {\"field\" : {\"message\" : \"?0\"}}}}")
Page<SampleEntity> findByMessage(String message, Pageable pageable);
@Query("{\"bool\" : {\"must\" : {\"field\" : {\"message\" : \"?0\"}}}}")
List<SampleEntity> findByMessage(String message);
@Query("{\"bool\" : {\"must\" : {\"field\" : {\"message\" : \"?0\"}}}}")
List<SampleEntity> findByMessage(String message);
Page<SampleEntity> findByAvailable(boolean available, Pageable pageable);
Page<SampleEntity> findByAvailable(boolean available, Pageable pageable);
Page<SampleEntity> findByRateLessThan(int rate, Pageable pageable);
Page<SampleEntity> findByRateLessThan(int rate, Pageable pageable);
Page<SampleEntity> findByRateBefore(int rate, Pageable pageable);
Page<SampleEntity> findByRateBefore(int rate, Pageable pageable);
Page<SampleEntity> findByRateAfter(int rate, Pageable pageable);
Page<SampleEntity> findByRateAfter(int rate, Pageable pageable);
Page<SampleEntity> findByMessageLike(String message, Pageable pageable);
Page<SampleEntity> findByMessageLike(String message, Pageable pageable);
Page<SampleEntity> findByMessageStartingWith(String message, Pageable pageable);
Page<SampleEntity> findByMessageStartingWith(String message, Pageable pageable);
Page<SampleEntity> findByMessageEndingWith(String message, Pageable pageable);
Page<SampleEntity> findByMessageEndingWith(String message, Pageable pageable);
Page<SampleEntity> findByMessageContaining(String message, Pageable pageable);
Page<SampleEntity> findByMessageContaining(String message, Pageable pageable);
Page<SampleEntity> findByIdIn(List<String> ids, Pageable pageable);
Page<SampleEntity> findByIdIn(List<String> ids, Pageable pageable);
Page<SampleEntity> findByIdNotIn(List<String> messages, Pageable pageable);
Page<SampleEntity> findByIdNotIn(List<String> messages, Pageable pageable);
Page<SampleEntity> findByAvailableTrue(Pageable pageable);
Page<SampleEntity> findByAvailableTrue(Pageable pageable);
Page<SampleEntity> findByAvailableFalse(Pageable pageable);
Page<SampleEntity> findByAvailableFalse(Pageable pageable);
Page<SampleEntity> findByMessageOrderByTypeAsc(String message,Pageable pageable);
Page<SampleEntity> findByMessageOrderByTypeAsc(String message, Pageable pageable);
}

View File

@ -24,5 +24,5 @@ import java.util.List;
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public interface SampleElasticSearchBookRepository extends ElasticsearchRepository<Book,String> {
public interface SampleElasticSearchBookRepository extends ElasticsearchRepository<Book, String> {
}

View File

@ -17,10 +17,11 @@ package org.springframework.data.elasticsearch.repositories;
import org.springframework.data.elasticsearch.SampleEntity;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
*/
public interface SampleElasticsearchRepository extends ElasticsearchRepository<SampleEntity,String> {
public interface SampleElasticsearchRepository extends ElasticsearchRepository<SampleEntity, String> {
}

View File

@ -38,51 +38,51 @@ import static org.junit.Assert.assertThat;
@ContextConfiguration("classpath:/simple-repository-test.xml")
public class DoubleIDRepositoryTests {
@Resource
private DoubleIDRepository repository;
@Resource
private DoubleIDRepository repository;
@Before
public void before(){
repository.deleteAll();
}
@Before
public void before() {
repository.deleteAll();
}
@Test
public void shouldDoBulkIndexDocument(){
//given
Double documentId1 = RandomUtils.nextDouble();
DoubleIDEntity sampleEntity1 = new DoubleIDEntity();
sampleEntity1.setId(documentId1);
sampleEntity1.setMessage("some message");
sampleEntity1.setVersion(System.currentTimeMillis());
@Test
public void shouldDoBulkIndexDocument() {
// given
Double documentId1 = RandomUtils.nextDouble();
DoubleIDEntity sampleEntity1 = new DoubleIDEntity();
sampleEntity1.setId(documentId1);
sampleEntity1.setMessage("some message");
sampleEntity1.setVersion(System.currentTimeMillis());
Double documentId2 = RandomUtils.nextDouble();
DoubleIDEntity sampleEntity2 = new DoubleIDEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("some message");
sampleEntity2.setVersion(System.currentTimeMillis());
Double documentId2 = RandomUtils.nextDouble();
DoubleIDEntity sampleEntity2 = new DoubleIDEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("some message");
sampleEntity2.setVersion(System.currentTimeMillis());
//when
repository.save(Arrays.asList(sampleEntity1, sampleEntity2));
//then
DoubleIDEntity entity1FromElasticSearch = repository.findOne(documentId1);
assertThat(entity1FromElasticSearch, is(notNullValue()));
// when
repository.save(Arrays.asList(sampleEntity1, sampleEntity2));
// then
DoubleIDEntity entity1FromElasticSearch = repository.findOne(documentId1);
assertThat(entity1FromElasticSearch, is(notNullValue()));
DoubleIDEntity entity2FromElasticSearch = repository.findOne(documentId2);
assertThat(entity2FromElasticSearch, is(notNullValue()));
}
DoubleIDEntity entity2FromElasticSearch = repository.findOne(documentId2);
assertThat(entity2FromElasticSearch, is(notNullValue()));
}
@Test
public void shouldSaveDocument(){
//given
Double documentId = RandomUtils.nextDouble();
DoubleIDEntity sampleEntity = new DoubleIDEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis());
//when
repository.save(sampleEntity);
//then
DoubleIDEntity entityFromElasticSearch = repository.findOne(documentId);
assertThat(entityFromElasticSearch, is(notNullValue()));
}
@Test
public void shouldSaveDocument() {
// given
Double documentId = RandomUtils.nextDouble();
DoubleIDEntity sampleEntity = new DoubleIDEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis());
// when
repository.save(sampleEntity);
// then
DoubleIDEntity entityFromElasticSearch = repository.findOne(documentId);
assertThat(entityFromElasticSearch, is(notNullValue()));
}
}

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch.repository.support;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@ -33,6 +32,7 @@ import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.DefaultRepositoryMetadata;
import static org.mockito.Mockito.when;
/**
* @author Rizwan Idrees
* @author Mohsin Husen
@ -40,27 +40,25 @@ import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class ElasticsearchRepositoryFactoryTests {
@Mock
private ElasticsearchOperations operations;
private ElasticsearchConverter converter;
private ElasticsearchRepositoryFactory factory;
MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext= new SimpleElasticsearchMappingContext();
@Mock
private ElasticsearchOperations operations;
private ElasticsearchConverter converter;
private ElasticsearchRepositoryFactory factory;
MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext = new SimpleElasticsearchMappingContext();
@Before
public void before(){
converter = new MappingElasticsearchConverter(mappingContext);
when(operations.getElasticsearchConverter()).thenReturn(converter);
factory = new ElasticsearchRepositoryFactory(operations);
}
@Before
public void before() {
converter = new MappingElasticsearchConverter(mappingContext);
when(operations.getElasticsearchConverter()).thenReturn(converter);
factory = new ElasticsearchRepositoryFactory(operations);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionGivenQueryDslRepository(){
//given
RepositoryMetadata metadata = new DefaultRepositoryMetadata(QueryDslPredicateExecutor.class);
//when
factory.getRepositoryBaseClass(metadata);
}
@Test(expected = IllegalArgumentException.class)
public void shouldThrowExceptionGivenQueryDslRepository() {
// given
RepositoryMetadata metadata = new DefaultRepositoryMetadata(QueryDslPredicateExecutor.class);
// when
factory.getRepositoryBaseClass(metadata);
}
}

View File

@ -38,51 +38,51 @@ import static org.junit.Assert.assertThat;
@ContextConfiguration("classpath:/simple-repository-test.xml")
public class IntegerIDRepositoryTests {
@Resource
private IntegerIDRepository repository;
@Resource
private IntegerIDRepository repository;
@Before
public void before(){
repository.deleteAll();
}
@Before
public void before() {
repository.deleteAll();
}
@Test
public void shouldDoBulkIndexDocument(){
//given
Integer documentId1 = RandomUtils.nextInt();
IntegerIDEntity sampleEntity1 = new IntegerIDEntity();
sampleEntity1.setId(documentId1);
sampleEntity1.setMessage("some message");
sampleEntity1.setVersion(System.currentTimeMillis());
@Test
public void shouldDoBulkIndexDocument() {
// given
Integer documentId1 = RandomUtils.nextInt();
IntegerIDEntity sampleEntity1 = new IntegerIDEntity();
sampleEntity1.setId(documentId1);
sampleEntity1.setMessage("some message");
sampleEntity1.setVersion(System.currentTimeMillis());
Integer documentId2 = RandomUtils.nextInt();
IntegerIDEntity sampleEntity2 = new IntegerIDEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("some message");
sampleEntity2.setVersion(System.currentTimeMillis());
Integer documentId2 = RandomUtils.nextInt();
IntegerIDEntity sampleEntity2 = new IntegerIDEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("some message");
sampleEntity2.setVersion(System.currentTimeMillis());
//when
repository.save(Arrays.asList(sampleEntity1, sampleEntity2));
//then
IntegerIDEntity entity1FromElasticSearch = repository.findOne(documentId1);
assertThat(entity1FromElasticSearch, is(notNullValue()));
// when
repository.save(Arrays.asList(sampleEntity1, sampleEntity2));
// then
IntegerIDEntity entity1FromElasticSearch = repository.findOne(documentId1);
assertThat(entity1FromElasticSearch, is(notNullValue()));
IntegerIDEntity entity2FromElasticSearch = repository.findOne(documentId2);
assertThat(entity2FromElasticSearch, is(notNullValue()));
}
IntegerIDEntity entity2FromElasticSearch = repository.findOne(documentId2);
assertThat(entity2FromElasticSearch, is(notNullValue()));
}
@Test
public void shouldSaveDocument(){
//given
Integer documentId = RandomUtils.nextInt();
IntegerIDEntity sampleEntity = new IntegerIDEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis());
//when
repository.save(sampleEntity);
//then
IntegerIDEntity entityFromElasticSearch = repository.findOne(documentId);
assertThat(entityFromElasticSearch, is(notNullValue()));
}
@Test
public void shouldSaveDocument() {
// given
Integer documentId = RandomUtils.nextInt();
IntegerIDEntity sampleEntity = new IntegerIDEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis());
// when
repository.save(sampleEntity);
// then
IntegerIDEntity entityFromElasticSearch = repository.findOne(documentId);
assertThat(entityFromElasticSearch, is(notNullValue()));
}
}

View File

@ -15,7 +15,6 @@
*/
package org.springframework.data.elasticsearch.repository.support;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@ -49,380 +48,367 @@ import static org.junit.Assert.*;
@ContextConfiguration("classpath:/simple-repository-test.xml")
public class SimpleElasticsearchRepositoryTests {
@Resource
private SampleElasticsearchRepository repository;
@Resource
private SampleElasticsearchRepository repository;
@Before
public void before() {
repository.deleteAll();
}
@Before
public void before(){
repository.deleteAll();
}
@Test
public void shouldDoBulkIndexDocument() {
// given
String documentId1 = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId1);
sampleEntity1.setMessage("some message");
sampleEntity1.setVersion(System.currentTimeMillis());
@Test
public void shouldDoBulkIndexDocument(){
//given
String documentId1 = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId1);
sampleEntity1.setMessage("some message");
sampleEntity1.setVersion(System.currentTimeMillis());
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("some message");
sampleEntity2.setVersion(System.currentTimeMillis());
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("some message");
sampleEntity2.setVersion(System.currentTimeMillis());
// when
repository.save(Arrays.asList(sampleEntity1, sampleEntity2));
// then
SampleEntity entity1FromElasticSearch = repository.findOne(documentId1);
assertThat(entity1FromElasticSearch, is(notNullValue()));
//when
repository.save(Arrays.asList(sampleEntity1, sampleEntity2));
//then
SampleEntity entity1FromElasticSearch = repository.findOne(documentId1);
assertThat(entity1FromElasticSearch, is(notNullValue()));
SampleEntity entity2FromElasticSearch = repository.findOne(documentId2);
assertThat(entity2FromElasticSearch, is(notNullValue()));
}
SampleEntity entity2FromElasticSearch = repository.findOne(documentId2);
assertThat(entity2FromElasticSearch, is(notNullValue()));
}
@Test
public void shouldSaveDocument() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis());
// when
repository.save(sampleEntity);
// then
SampleEntity entityFromElasticSearch = repository.findOne(documentId);
assertThat(entityFromElasticSearch, is(notNullValue()));
}
@Test
public void shouldSaveDocument(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis());
//when
repository.save(sampleEntity);
//then
SampleEntity entityFromElasticSearch = repository.findOne(documentId);
assertThat(entityFromElasticSearch, is(notNullValue()));
}
@Test
public void shouldFindDocumentById() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
// when
SampleEntity entityFromElasticSearch = repository.findOne(documentId);
// then
assertThat(entityFromElasticSearch, is(notNullValue()));
assertThat(sampleEntity, is((equalTo(sampleEntity))));
}
@Test
public void shouldFindDocumentById(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
//when
SampleEntity entityFromElasticSearch = repository.findOne(documentId);
//then
assertThat(entityFromElasticSearch, is(notNullValue()));
assertThat(sampleEntity, is((equalTo(sampleEntity))));
}
@Test
public void shouldReturnCountOfDocuments() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
// when
Long count = repository.count();
// then
assertThat(count, is(greaterThanOrEqualTo(1L)));
}
@Test
public void shouldReturnCountOfDocuments(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
//when
Long count = repository.count();
//then
assertThat(count, is(greaterThanOrEqualTo(1L)));
}
@Test
public void shouldFindAllDocuments() {
// when
Iterable<SampleEntity> results = repository.findAll();
// then
assertThat(results, is(notNullValue()));
}
@Test
public void shouldFindAllDocuments(){
//when
Iterable<SampleEntity> results = repository.findAll();
//then
assertThat(results, is(notNullValue()));
}
@Test
public void shouldDeleteDocument() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
// when
repository.delete(documentId);
// then
SampleEntity entityFromElasticSearch = repository.findOne(documentId);
assertThat(entityFromElasticSearch, is(nullValue()));
}
@Test
public void shouldDeleteDocument(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
//when
repository.delete(documentId);
//then
SampleEntity entityFromElasticSearch = repository.findOne(documentId);
assertThat(entityFromElasticSearch, is(nullValue()));
}
@Test
public void shouldSearchDocumentsGivenSearchQuery() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("some test message");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
@Test
public void shouldSearchDocumentsGivenSearchQuery(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("some test message");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
SearchQuery query = new NativeSearchQueryBuilder().withQuery(termQuery("message", "test")).build();
// when
Page<SampleEntity> page = repository.search(query);
// then
assertThat(page, is(notNullValue()));
assertThat(page.getNumberOfElements(), is(greaterThanOrEqualTo(1)));
}
SearchQuery query = new NativeSearchQueryBuilder()
.withQuery(termQuery("message", "test"))
.build();
//when
Page<SampleEntity> page = repository.search(query);
//then
assertThat(page, is(notNullValue()));
assertThat(page.getNumberOfElements(), is(greaterThanOrEqualTo(1)));
}
@Test
public void shouldSearchDocumentsGivenElasticsearchQuery() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("hello world.");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
// when
Page<SampleEntity> page = repository.search(termQuery("message", "world"), new PageRequest(0, 50));
// then
assertThat(page, is(notNullValue()));
assertThat(page.getNumberOfElements(), is(greaterThanOrEqualTo(1)));
}
@Test
public void shouldSearchDocumentsGivenElasticsearchQuery(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("hello world.");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
//when
Page<SampleEntity> page = repository.search(termQuery("message", "world"), new PageRequest(0,50));
//then
assertThat(page, is(notNullValue()));
assertThat(page.getNumberOfElements(), is(greaterThanOrEqualTo(1)));
}
@Test
@Ignore
public void shouldFindAllByIdQuery() {
// todo : find solution for findAll(Iterable<Ids> ids)
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("hello world.");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
@Test
@Ignore
public void shouldFindAllByIdQuery(){
//todo : find solution for findAll(Iterable<Ids> ids)
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("hello world.");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("hello world.");
sampleEntity2.setVersion(System.currentTimeMillis());
repository.save(sampleEntity2);
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("hello world.");
sampleEntity2.setVersion(System.currentTimeMillis());
repository.save(sampleEntity2);
// when
Iterable<SampleEntity> sampleEntities = repository.findAll(Arrays.asList(documentId, documentId2));
//when
Iterable<SampleEntity> sampleEntities=repository.findAll(Arrays.asList(documentId,documentId2));
// then
assertNotNull("sample entities cant be null..", sampleEntities);
}
//then
assertNotNull("sample entities cant be null..", sampleEntities);
}
@Test
public void shouldSaveIterableEntities() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId);
sampleEntity1.setMessage("hello world.");
sampleEntity1.setVersion(System.currentTimeMillis());
@Test
public void shouldSaveIterableEntities(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId);
sampleEntity1.setMessage("hello world.");
sampleEntity1.setVersion(System.currentTimeMillis());
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("hello world.");
sampleEntity2.setVersion(System.currentTimeMillis());
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("hello world.");
sampleEntity2.setVersion(System.currentTimeMillis());
Iterable<SampleEntity> sampleEntities = Arrays.asList(sampleEntity1, sampleEntity2);
// when
repository.save(sampleEntities);
// then
Page<SampleEntity> entities = repository.search(fieldQuery("id", documentId), new PageRequest(0, 50));
assertNotNull(entities);
}
Iterable<SampleEntity> sampleEntities = Arrays.asList(sampleEntity1,sampleEntity2);
//when
repository.save(sampleEntities);
//then
Page<SampleEntity> entities = repository.search(fieldQuery("id", documentId), new PageRequest(0, 50));
assertNotNull(entities);
}
@Test
public void shouldReturnTrueGivenDocumentWithIdExists() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("hello world.");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
@Test
public void shouldReturnTrueGivenDocumentWithIdExists(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("hello world.");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
// when
boolean exist = repository.exists(documentId);
//when
boolean exist = repository.exists(documentId);
// then
assertEquals(exist, true);
}
//then
assertEquals(exist, true);
}
@Test
public void shouldReturnResultsForGivenSearchQuery() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("hello world.");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
// when
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fieldQuery("id", documentId)).build();
Page<SampleEntity> sampleEntities = repository.search(searchQuery);
// then
assertThat(sampleEntities.getTotalElements(), equalTo(1L));
}
@Test
public void shouldReturnResultsForGivenSearchQuery(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("hello world.");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
//when
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(fieldQuery("id",documentId))
.build();
Page<SampleEntity> sampleEntities= repository.search(searchQuery);
//then
assertThat(sampleEntities.getTotalElements(), equalTo(1L));
}
@Test
public void shouldDeleteAll() {
// when
repository.deleteAll();
// then
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
Page<SampleEntity> sampleEntities = repository.search(searchQuery);
assertThat(sampleEntities.getTotalElements(), equalTo(0L));
}
@Test
public void shouldDeleteAll(){
//when
repository.deleteAll();
//then
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchAllQuery())
.build();
Page<SampleEntity> sampleEntities= repository.search(searchQuery);
assertThat(sampleEntities.getTotalElements(), equalTo(0L));
}
@Test
public void shouldDeleteEntity() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("hello world.");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
// when
repository.delete(sampleEntity);
// then
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fieldQuery("id", documentId)).build();
Page<SampleEntity> sampleEntities = repository.search(searchQuery);
assertThat(sampleEntities.getTotalElements(), equalTo(0L));
}
@Test
public void shouldDeleteEntity(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("hello world.");
sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity);
//when
repository.delete(sampleEntity);
//then
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(fieldQuery("id", documentId))
.build();
Page<SampleEntity> sampleEntities= repository.search(searchQuery);
assertThat(sampleEntities.getTotalElements(),equalTo(0L));
}
@Test
public void shouldReturnIterableEntities() {
// given
String documentId1 = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId1);
sampleEntity1.setMessage("hello world.");
sampleEntity1.setVersion(System.currentTimeMillis());
repository.save(sampleEntity1);
@Test
public void shouldReturnIterableEntities(){
//given
String documentId1 = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId1);
sampleEntity1.setMessage("hello world.");
sampleEntity1.setVersion(System.currentTimeMillis());
repository.save(sampleEntity1);
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("hello world.");
sampleEntity2.setVersion(System.currentTimeMillis());
repository.save(sampleEntity2);
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("hello world.");
sampleEntity2.setVersion(System.currentTimeMillis());
repository.save(sampleEntity2);
// when
Iterable<SampleEntity> sampleEntities = repository.search(fieldQuery("id", documentId1));
// then
assertNotNull("sample entities cant be null..", sampleEntities);
}
//when
Iterable<SampleEntity> sampleEntities = repository.search(fieldQuery("id",documentId1));
//then
assertNotNull("sample entities cant be null..", sampleEntities);
}
@Test
public void shouldDeleteIterableEntities() {
// given
String documentId1 = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId1);
sampleEntity1.setMessage("hello world.");
sampleEntity1.setVersion(System.currentTimeMillis());
@Test
public void shouldDeleteIterableEntities(){
//given
String documentId1 = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId1);
sampleEntity1.setMessage("hello world.");
sampleEntity1.setVersion(System.currentTimeMillis());
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("hello world.");
sampleEntity2.setVersion(System.currentTimeMillis());
repository.save(sampleEntity2);
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("hello world.");
sampleEntity2.setVersion(System.currentTimeMillis());
repository.save(sampleEntity2);
Iterable<SampleEntity> sampleEntities = Arrays.asList(sampleEntity2, sampleEntity2);
// when
repository.delete(sampleEntities);
// then
assertThat(repository.findOne(documentId1), is(nullValue()));
assertThat(repository.findOne(documentId2), is(nullValue()));
}
Iterable<SampleEntity> sampleEntities = Arrays.asList(sampleEntity2,sampleEntity2);
//when
repository.delete(sampleEntities);
//then
assertThat(repository.findOne(documentId1),is(nullValue()));
assertThat(repository.findOne(documentId2),is(nullValue()));
}
@Test
public void shouldIndexEntity() {
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setVersion(System.currentTimeMillis());
sampleEntity.setMessage("some message");
// when
repository.index(sampleEntity);
// then
Page<SampleEntity> entities = repository.search(fieldQuery("id", documentId), new PageRequest(0, 50));
assertThat(entities.getTotalElements(), equalTo(1L));
}
@Test
public void shouldIndexEntity(){
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setVersion(System.currentTimeMillis());
sampleEntity.setMessage("some message");
//when
repository.index(sampleEntity);
//then
Page<SampleEntity> entities = repository.search(fieldQuery("id", documentId), new PageRequest(0,50));
assertThat(entities.getTotalElements(),equalTo(1L));
}
@Test
public void shouldSortByGivenField() {
// todo
// given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("world");
repository.save(sampleEntity);
@Test
public void shouldSortByGivenField(){
//todo
//given
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage("world");
repository.save(sampleEntity);
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("hello");
repository.save(sampleEntity2);
// when
Iterable<SampleEntity> sampleEntities = repository.findAll(new Sort(new Sort.Order(Sort.Direction.ASC, "message")));
// then
assertThat(sampleEntities, is(notNullValue()));
}
String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("hello");
repository.save(sampleEntity2);
//when
Iterable<SampleEntity> sampleEntities=repository.findAll(new Sort(new Sort.Order(Sort.Direction.ASC,"message")));
//then
assertThat(sampleEntities,is(notNullValue()));
}
@Test
public void shouldReturnSimilarEntities() {
// given
String sampleMessage = "So we build a web site or an application and want to add search to it, "
+ "and then it hits us: getting search working is hard. We want our search solution to be fast,"
+ " we want a painless setup and a completely free search schema, we want to be able to index data simply using JSON over HTTP, "
+ "we want our search server to be always available, we want to be able to start with one machine and scale to hundreds, "
+ "we want real-time search, we want simple multi-tenancy, and we want a solution that is built for the cloud.";
@Test
public void shouldReturnSimilarEntities(){
//given
String sampleMessage = "So we build a web site or an application and want to add search to it, " +
"and then it hits us: getting search working is hard. We want our search solution to be fast," +
" we want a painless setup and a completely free search schema, we want to be able to index data simply using JSON over HTTP, " +
"we want our search server to be always available, we want to be able to start with one machine and scale to hundreds, " +
"we want real-time search, we want simple multi-tenancy, and we want a solution that is built for the cloud.";
List<SampleEntity> sampleEntities = createSampleEntitiesWithMessage(sampleMessage, 30);
repository.save(sampleEntities);
// when
SearchQuery searchQuery = new NativeSearchQueryBuilder().withPageable(new PageRequest(0, 5)).withFields("message")
.build();
Page<SampleEntity> results = repository.searchSimilar(sampleEntities.get(0), searchQuery);
// then
assertThat(results.getTotalElements(), is(greaterThanOrEqualTo(1L)));
}
List<SampleEntity> sampleEntities = createSampleEntitiesWithMessage(sampleMessage, 30);
repository.save(sampleEntities);
//when
SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withPageable(new PageRequest(0, 5))
.withFields("message")
.build();
Page<SampleEntity> results = repository.searchSimilar(sampleEntities.get(0), searchQuery);
//then
assertThat(results.getTotalElements(), is(greaterThanOrEqualTo(1L)));
}
private static List<SampleEntity> createSampleEntitiesWithMessage(String message, int numberOfEntities){
List<SampleEntity> sampleEntities = new ArrayList<SampleEntity>();
for(int i = 0; i < numberOfEntities; i++){
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage(message);
sampleEntity.setRate(2);
sampleEntity.setVersion(System.currentTimeMillis());
sampleEntities.add(sampleEntity);
}
return sampleEntities;
}
private static List<SampleEntity> createSampleEntitiesWithMessage(String message, int numberOfEntities) {
List<SampleEntity> sampleEntities = new ArrayList<SampleEntity>();
for (int i = 0; i < numberOfEntities; i++) {
String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId);
sampleEntity.setMessage(message);
sampleEntity.setRate(2);
sampleEntity.setVersion(System.currentTimeMillis());
sampleEntities.add(sampleEntity);
}
return sampleEntities;
}
}

View File

@ -1,18 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
xsi:schemaLocation="http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
xsi:schemaLocation="http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<import resource="infrastructure.xml" />
<import resource="infrastructure.xml" />
<bean name="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="client"/>
</bean>
<bean name="elasticsearchTemplate"
class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="client" />
</bean>
<elasticsearch:repositories base-package="org.springframework.data.elasticsearch.repositories" />
<elasticsearch:repositories
base-package="org.springframework.data.elasticsearch.repositories" />
</beans>

View File

@ -1,14 +1,15 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
xsi:schemaLocation="http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
xsi:schemaLocation="http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd">
<import resource="infrastructure.xml" />
<import resource="infrastructure.xml" />
<bean name="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="client"/>
</bean>
<bean name="elasticsearchTemplate"
class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="client" />
</bean>
</beans>

View File

@ -1,10 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
xsi:schemaLocation="http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch.xsd
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:elasticsearch="http://www.springframework.org/schema/data/elasticsearch"
xsi:schemaLocation="http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<elasticsearch:node-client id="client" local="true" cluster-name="testCluster" http-enabled="false" />
<elasticsearch:node-client id="client" local="true"
cluster-name="testCluster" http-enabled="false" />
</beans>

Some files were not shown because too many files have changed in this diff Show More