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>

View File

@ -1,5 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?> <?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"> <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> <modelVersion>4.0.0</modelVersion>
<groupId>org.springframework.data</groupId> <groupId>org.springframework.data</groupId>
@ -154,12 +155,13 @@
<scm> <scm>
<url>https://github.com/SpringSource/spring-data-elasticsearch</url> <url>https://github.com/SpringSource/spring-data-elasticsearch</url>
<connection>scm:git:git://github.com/SpringSource/spring-data-elasticsearch.git</connection> <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> <developerConnection>scm:git:ssh://git@github.com:SpringSource/spring-data-elasticsearch.git
</developerConnection>
</scm> </scm>
<ciManagement> <ciManagement>
<system>Bamboo</system> <system>Bamboo</system>
<url>http://build.springsource.org/browse/SPRINGDATAESh</url> <url>http://build.springsource.org/browse/SPRINGDATAES</url>
</ciManagement> </ciManagement>
<issueManagement> <issueManagement>

View File

@ -35,8 +35,10 @@
<part id="reference"> <part id="reference">
<title>Reference Documentation</title> <title>Reference Documentation</title>
<xi:include href="https://raw.github.com/SpringSource/spring-data-commons/1.4.0.RC1/src/docbkx/repositories.xml"> <xi:include
<xi:fallback href="../../../spring-data-commons/src/docbkx/repositories.xml" /> 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>
<xi:include href="reference/data-elasticsearch.xml" /> <xi:include href="reference/data-elasticsearch.xml" />

View File

@ -3,11 +3,14 @@
"http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd"> "http://www.oasis-open.org/docbook/xml/4.4/docbookx.dtd">
<preface id="preface"> <preface id="preface">
<title>Preface</title> <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 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 We have povided a "template" as a high-level abstraction for
storing,querying,sorting and faceting documents. You will notice similarities storing,querying,sorting and faceting documents. You will notice
similarities
to the Spring data solr and to the Spring data solr and
mongodb support in the Spring Framework. mongodb support in the Spring Framework.
</para> </para>
@ -17,7 +20,8 @@
<listitem> <listitem>
<para> <para>
Version Control - 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> </ulink>
</para> </para>
</listitem> </listitem>
@ -28,7 +32,8 @@
<para> <para>
Requires Requires
<ulink url="http://www.elasticsearch.org/download/">Elasticsearch</ulink> <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 0.20.2 and above or optional dependency or not even that if you are
using Embedded Node Client
</para> </para>
</section> </section>
</preface> </preface>

View File

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

View File

@ -8,7 +8,8 @@
This chapter covers additional support for Elasticsearch operations 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. interface.
It is recommended to add those operations as custom It is
recommended to add those operations as custom
implementation as implementation as
described in described in
<xref linkend="repositories.custom-implementations" /> <xref linkend="repositories.custom-implementations" />
@ -21,7 +22,7 @@
Filter Builder improves query speed. Filter Builder improves query speed.
</para> </para>
<example> <example>
<programlisting language="java"> <programlisting language="java">
private ElasticsearchTemplate elasticsearchTemplate; private ElasticsearchTemplate elasticsearchTemplate;
SearchQuery searchQuery = new NativeSearchQueryBuilder() SearchQuery searchQuery = new NativeSearchQueryBuilder()
.withQuery(matchAllQuery()) .withQuery(matchAllQuery())
@ -34,7 +35,8 @@ Page&lt;SampleEntity&gt; sampleEntities = elasticsearchTemplate.queryForPage(sea
<section id="elasticsearch.scan.and.scroll"> <section id="elasticsearch.scan.and.scroll">
<title>Using Scan And Scroll For Big Result Set</title> <title>Using Scan And Scroll For Big Result Set</title>
<para> <para>
Elasticsearch has scan and scroll feature for getting big result set in chunks. Elasticsearch has scan and scroll feature for getting big result set
in chunks.
<interfacename>ElasticsearchTemplate</interfacename> <interfacename>ElasticsearchTemplate</interfacename>
has scan and scroll methods that can be used as below. has scan and scroll methods that can be used as below.
</para> </para>

File diff suppressed because it is too large Load Diff

View File

@ -3,7 +3,6 @@
code highlight CSS resemblign the Eclipse IDE default color schema code highlight CSS resemblign the Eclipse IDE default color schema
@author Costin Leau @author Costin Leau
*/ */
.hl-keyword { .hl-keyword {
color: #7F0055; color: #7F0055;
font-weight: bold; font-weight: bold;

View File

@ -1,7 +1,6 @@
/* /*
borrowed from: https://raw.github.com/SpringSource/spring-data-jpa/master/src/docbkx/resources/css/html.css borrowed from: https://raw.github.com/SpringSource/spring-data-jpa/master/src/docbkx/resources/css/html.css
*/ */
@IMPORT url("highlight.css"); @IMPORT url("highlight.css");
html { html {
@ -12,7 +11,8 @@ html {
body { body {
margin-left: 15%; margin-left: 15%;
margin-right: 15%; margin-right: 15%;
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande",
sans-serif;
} }
div { div {
@ -31,7 +31,8 @@ hr {
h1,h2,h3,h4,h5 { h1,h2,h3,h4,h5 {
color: #234623; color: #234623;
font-weight: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; font-weight: "Helvetica Neue", Helvetica, Arial, "Lucida Grande",
sans-serif;
margin-bottom: 0em; margin-bottom: 0em;
margin-top: 2em; margin-top: 2em;
} }
@ -85,7 +86,8 @@ div.table td {
} }
.legalnotice { .legalnotice {
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande",
sans-serif;
font-size: 12px; font-size: 12px;
font-style: italic; font-style: italic;
} }
@ -93,20 +95,23 @@ div.table td {
p.releaseinfo { p.releaseinfo {
font-size: 100%; font-size: 100%;
font-weight: bold; font-weight: bold;
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande",
sans-serif;
padding-top: 10px; padding-top: 10px;
} }
p.pubdate { p.pubdate {
font-size: 120%; font-size: 120%;
font-weight: bold; font-weight: bold;
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande",
sans-serif;
} }
span.productname { span.productname {
font-size: 200%; font-size: 200%;
font-weight: bold; font-weight: bold;
font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; font-family: "Helvetica Neue", Helvetica, Arial, "Lucida Grande",
sans-serif;
} }
code { code {

View File

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

View File

@ -1,45 +1,57 @@
<?xml version='1.0'?> <?xml version='1.0'?>
<!-- <!-- borrowed from: https://raw.github.com/SpringSource/spring-data-jpa/master/src/docbkx/resources/xsl/highlight-fo.xsl
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. -->
Simple highlighter for FO/PDF output. Follows the Eclipse color scheme.
-->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" <xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xslthl="http://xslthl.sf.net"
xmlns:xslthl="http://xslthl.sf.net" exclude-result-prefixes="xslthl" version='1.0'>
exclude-result-prefixes="xslthl"
version='1.0'>
<xsl:template match='xslthl:keyword'> <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>
<xsl:template match='xslthl:comment'> <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>
<xsl:template match='xslthl:oneline-comment'> <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>
<xsl:template match='xslthl:multiline-comment'> <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>
<xsl:template match='xslthl:tag'> <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>
<xsl:template match='xslthl:attribute'> <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>
<xsl:template match='xslthl:value'> <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>
<xsl:template match='xslthl:string'> <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:template>
</xsl:stylesheet> </xsl:stylesheet>

View File

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

View File

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

View File

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

View File

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

View File

@ -1,4 +1,5 @@
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0" <assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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"> 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> <id>all</id>

View File

@ -15,7 +15,6 @@
*/ */
package org.springframework.data.elasticsearch; package org.springframework.data.elasticsearch;
import java.util.Map; import java.util.Map;
/** /**
@ -24,7 +23,7 @@ import java.util.Map;
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
*/ */
public class ElasticsearchException extends RuntimeException{ public class ElasticsearchException extends RuntimeException {
private Map<String, String> failedDocuments; private Map<String, String> failedDocuments;

View File

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

View File

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

View File

@ -65,11 +65,11 @@ public class NodeClientFactoryBean implements FactoryBean<NodeClient>, Initializ
@Override @Override
public void afterPropertiesSet() throws Exception { public void afterPropertiesSet() throws Exception {
ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder() ImmutableSettings.Builder settings = ImmutableSettings.settingsBuilder().put("http.enabled",
.put("http.enabled", String.valueOf(this.enableHttp)); String.valueOf(this.enableHttp));
nodeClient = (NodeClient) nodeBuilder().settings(settings) nodeClient = (NodeClient) nodeBuilder().settings(settings).clusterName(this.clusterName).local(this.local).node()
.clusterName(this.clusterName).local(this.local).node().client(); .client();
} }
public void setLocal(boolean local) { public void setLocal(boolean local) {

View File

@ -80,24 +80,23 @@ public class TransportClientFactoryBean implements FactoryBean<TransportClient>,
protected void buildClient() throws Exception { protected void buildClient() throws Exception {
client = new TransportClient(settings()); client = new TransportClient(settings());
Assert.notEmpty(clusterNodes,"[Assertion failed] clusterNodes settings missing."); Assert.notEmpty(clusterNodes, "[Assertion failed] clusterNodes settings missing.");
for (String clusterNode : clusterNodes) { for (String clusterNode : clusterNodes) {
String hostName = substringBefore(clusterNode, COLON); String hostName = substringBefore(clusterNode, COLON);
String port = substringAfter(clusterNode, COLON); String port = substringAfter(clusterNode, COLON);
Assert.hasText(hostName,"[Assertion failed] missing host name in 'clusterNodes'"); Assert.hasText(hostName, "[Assertion failed] missing host name in 'clusterNodes'");
Assert.hasText(port,"[Assertion failed] missing port in 'clusterNodes'"); Assert.hasText(port, "[Assertion failed] missing port in 'clusterNodes'");
logger.info("adding transport node : " + clusterNode); logger.info("adding transport node : " + clusterNode);
client.addTransportAddress(new InetSocketTransportAddress(hostName, Integer.valueOf(port))); client.addTransportAddress(new InetSocketTransportAddress(hostName, Integer.valueOf(port)));
} }
client.connectedNodes(); client.connectedNodes();
} }
private Settings settings(){ private Settings settings() {
if(properties != null){ if (properties != null) {
return settingsBuilder().put(properties).build(); return settingsBuilder().put(properties).build();
} }
return settingsBuilder() return settingsBuilder().put("client.transport.sniff", true).build();
.put("client.transport.sniff",true).build();
} }
public void setClusterNodes(String[] clusterNodes) { public void setClusterNodes(String[] clusterNodes) {

View File

@ -27,7 +27,7 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
* @author Mohsin Husen * @author Mohsin Husen
*/ */
public class ElasticsearchNamespaceHandler extends NamespaceHandlerSupport{ public class ElasticsearchNamespaceHandler extends NamespaceHandlerSupport {
@Override @Override
public void init() { public void init() {

View File

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

View File

@ -23,6 +23,7 @@ import org.springframework.data.elasticsearch.client.TransportClientFactoryBean;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import static org.apache.commons.lang.StringUtils.split; import static org.apache.commons.lang.StringUtils.split;
/** /**
* TransportClientBeanDefinitionParser * TransportClientBeanDefinitionParser
* *
@ -38,10 +39,10 @@ public class TransportClientBeanDefinitionParser extends AbstractBeanDefinitionP
protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TransportClientFactoryBean.class); BeanDefinitionBuilder builder = BeanDefinitionBuilder.rootBeanDefinition(TransportClientFactoryBean.class);
setClusterNodes(element, builder); setClusterNodes(element, builder);
return getSourcedBeanDefinition(builder,element, parserContext); return getSourcedBeanDefinition(builder, element, parserContext);
} }
private void setClusterNodes(Element element, BeanDefinitionBuilder builder){ private void setClusterNodes(Element element, BeanDefinitionBuilder builder) {
builder.addPropertyValue("clusterNodes", split(element.getAttribute("cluster-nodes"), SEPARATOR_CHARS)); builder.addPropertyValue("clusterNodes", split(element.getAttribute("cluster-nodes"), SEPARATOR_CHARS));
} }

View File

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

View File

@ -15,7 +15,6 @@
*/ */
package org.springframework.data.elasticsearch.core; package org.springframework.data.elasticsearch.core;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter; import org.springframework.data.elasticsearch.core.convert.ElasticsearchConverter;
import org.springframework.data.elasticsearch.core.query.*; import org.springframework.data.elasticsearch.core.query.*;
@ -30,7 +29,6 @@ import java.util.List;
*/ */
public interface ElasticsearchOperations { public interface ElasticsearchOperations {
/** /**
* @return Converter in use * @return Converter in use
*/ */
@ -38,6 +36,7 @@ public interface ElasticsearchOperations {
/** /**
* Create an index for a class * Create an index for a class
*
* @param clazz * @param clazz
* @param <T> * @param <T>
*/ */
@ -45,12 +44,12 @@ public interface ElasticsearchOperations {
/** /**
* Create mapping for a class * Create mapping for a class
*
* @param clazz * @param clazz
* @param <T> * @param <T>
*/ */
<T> boolean putMapping(Class<T> clazz); <T> boolean putMapping(Class<T> clazz);
/** /**
* Execute the query against elasticsearch and return the first returned object * Execute the query against elasticsearch and return the first returned object
* *
@ -69,7 +68,6 @@ public interface ElasticsearchOperations {
*/ */
<T> T queryForObject(CriteriaQuery query, Class<T> clazz); <T> T queryForObject(CriteriaQuery query, Class<T> clazz);
/** /**
* Execute the query against elasticsearch and return the first returned object * Execute the query against elasticsearch and return the first returned object
* *
@ -79,7 +77,6 @@ public interface ElasticsearchOperations {
*/ */
<T> T queryForObject(StringQuery query, Class<T> clazz); <T> T queryForObject(StringQuery query, Class<T> clazz);
/** /**
* Execute the query against elasticsearch and return result as {@link Page} * Execute the query against elasticsearch and return result as {@link Page}
* *
@ -89,7 +86,6 @@ public interface ElasticsearchOperations {
*/ */
<T> Page<T> queryForPage(SearchQuery query, Class<T> clazz); <T> Page<T> queryForPage(SearchQuery query, Class<T> clazz);
/** /**
* Execute the query against elasticsearch and return result as {@link Page} * Execute the query against elasticsearch and return result as {@link Page}
* *
@ -99,7 +95,6 @@ public interface ElasticsearchOperations {
*/ */
<T> Page<T> queryForPage(SearchQuery query, ResultsMapper<T> resultsMapper); <T> Page<T> queryForPage(SearchQuery query, ResultsMapper<T> resultsMapper);
/** /**
* Execute the query against elasticsearch and return result as {@link Page} * Execute the query against elasticsearch and return result as {@link Page}
* *
@ -109,7 +104,6 @@ public interface ElasticsearchOperations {
*/ */
<T> Page<T> queryForPage(CriteriaQuery query, Class<T> clazz); <T> Page<T> queryForPage(CriteriaQuery query, Class<T> clazz);
/** /**
* Execute the query against elasticsearch and return result as {@link Page} * Execute the query against elasticsearch and return result as {@link Page}
* *
@ -192,6 +186,7 @@ public interface ElasticsearchOperations {
/** /**
* Delete all records matching the query * Delete all records matching the query
*
* @param clazz * @param clazz
* @param query * @param query
*/ */
@ -199,6 +194,7 @@ public interface ElasticsearchOperations {
/** /**
* Deletes an index for given entity * Deletes an index for given entity
*
* @param clazz * @param clazz
* @param <T> * @param <T>
* @return * @return
@ -207,6 +203,7 @@ public interface ElasticsearchOperations {
/** /**
* check if index is exists * check if index is exists
*
* @param clazz * @param clazz
* @param <T> * @param <T>
* @return * @return
@ -215,20 +212,23 @@ public interface ElasticsearchOperations {
/** /**
* refresh the index * refresh the index
*
* @param indexName * @param indexName
* @param waitForOperation * @param waitForOperation
*/ */
void refresh(String indexName,boolean waitForOperation); void refresh(String indexName, boolean waitForOperation);
/** /**
* refresh the index * refresh the index
*
* @param clazz * @param clazz
* @param waitForOperation * @param waitForOperation
*/ */
<T> void refresh(Class<T> clazz,boolean waitForOperation); <T> void refresh(Class<T> clazz, boolean waitForOperation);
/** /**
* Returns scroll id for scan query * Returns scroll id for scan query
*
* @param query * @param query
* @param scrollTimeInMillis * @param scrollTimeInMillis
* @param noFields * @param noFields
@ -238,6 +238,7 @@ public interface ElasticsearchOperations {
/** /**
* Scrolls the results for give scroll id * Scrolls the results for give scroll id
*
* @param scrollId * @param scrollId
* @param scrollTimeInMillis * @param scrollTimeInMillis
* @param resultsMapper * @param resultsMapper
@ -248,6 +249,7 @@ public interface ElasticsearchOperations {
/** /**
* more like this query to search for documents that are "like" a specific document. * more like this query to search for documents that are "like" a specific document.
*
* @param query * @param query
* @param clazz * @param clazz
* @param <T> * @param <T>

View File

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

View File

@ -15,7 +15,6 @@
*/ */
package org.springframework.data.elasticsearch.core; package org.springframework.data.elasticsearch.core;
import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentBuilder;
import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.Field;
import org.springframework.data.mapping.model.SimpleTypeHolder; import org.springframework.data.mapping.model.SimpleTypeHolder;
@ -39,68 +38,59 @@ 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 { static XContentBuilder buildMapping(Class clazz, String indexType, String idFieldName) throws IOException {
XContentBuilder xContentBuilder = jsonBuilder() XContentBuilder xContentBuilder = jsonBuilder().startObject().startObject(indexType).startObject("properties");
.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, private static void mapEntity(XContentBuilder xContentBuilder, Class clazz, boolean isRootObject, String idFieldName,
Class clazz, String nestedObjectFieldName) throws IOException {
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)){ if (!isRootObject && isAnyPropertyAnnotatedAsField(fields)) {
xContentBuilder.startObject(nestedObjectFieldName) xContentBuilder.startObject(nestedObjectFieldName).field("type", "object").startObject("properties");
.field("type", "object")
.startObject("properties");
} }
for(java.lang.reflect.Field field : fields){ for (java.lang.reflect.Field field : fields) {
if(isEntity(field)){ if (isEntity(field)) {
mapEntity(xContentBuilder, field.getType(), false, EMPTY, field.getName()); mapEntity(xContentBuilder, field.getType(), false, EMPTY, field.getName());
} }
Field fieldAnnotation = field.getAnnotation(Field.class); Field fieldAnnotation = field.getAnnotation(Field.class);
if(isRootObject && fieldAnnotation != null && isIdField(field, idFieldName)){ if (isRootObject && fieldAnnotation != null && isIdField(field, idFieldName)) {
applyDefaultIdFieldMapping(xContentBuilder, field); applyDefaultIdFieldMapping(xContentBuilder, field);
}else if(fieldAnnotation != null){ } else if (fieldAnnotation != null) {
applyFieldAnnotationMapping(xContentBuilder, field, fieldAnnotation); applyFieldAnnotationMapping(xContentBuilder, field, fieldAnnotation);
} }
} }
if(!isRootObject && isAnyPropertyAnnotatedAsField(fields)){ if (!isRootObject && isAnyPropertyAnnotatedAsField(fields)) {
xContentBuilder.endObject().endObject(); xContentBuilder.endObject().endObject();
} }
} }
private static void applyDefaultIdFieldMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field) throws IOException { private static void applyDefaultIdFieldMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field)
xContentBuilder.startObject(field.getName()) throws IOException {
.field("type", "string") xContentBuilder.startObject(field.getName()).field("type", "string").field("index", "not_analyzed").endObject();
.field("index", "not_analyzed")
.endObject();
} }
private static void applyFieldAnnotationMapping(XContentBuilder xContentBuilder, private static void applyFieldAnnotationMapping(XContentBuilder xContentBuilder, java.lang.reflect.Field field,
java.lang.reflect.Field field,
Field fieldAnnotation) throws IOException { Field fieldAnnotation) throws IOException {
xContentBuilder.startObject(field.getName()); xContentBuilder.startObject(field.getName());
xContentBuilder.field("store", fieldAnnotation.store()); xContentBuilder.field("store", fieldAnnotation.store());
if(isNotBlank(fieldAnnotation.type())){ if (isNotBlank(fieldAnnotation.type())) {
xContentBuilder.field("type", fieldAnnotation.type()); xContentBuilder.field("type", fieldAnnotation.type());
} }
if(isNotBlank(fieldAnnotation.index())){ if (isNotBlank(fieldAnnotation.index())) {
xContentBuilder.field("index", fieldAnnotation.index()); xContentBuilder.field("index", fieldAnnotation.index());
} }
if(isNotBlank(fieldAnnotation.searchAnalyzer())){ if (isNotBlank(fieldAnnotation.searchAnalyzer())) {
xContentBuilder.field("search_analyzer", fieldAnnotation.searchAnalyzer()); xContentBuilder.field("search_analyzer", fieldAnnotation.searchAnalyzer());
} }
if(isNotBlank(fieldAnnotation.indexAnalyzer())){ if (isNotBlank(fieldAnnotation.indexAnalyzer())) {
xContentBuilder.field("index_analyzer", fieldAnnotation.indexAnalyzer()); xContentBuilder.field("index_analyzer", fieldAnnotation.indexAnalyzer());
} }
xContentBuilder.endObject(); xContentBuilder.endObject();
@ -113,10 +103,10 @@ class MappingBuilder {
return isComplexType && !actualType.isCollectionLike() && !Map.class.isAssignableFrom(typeInformation.getType()); return isComplexType && !actualType.isCollectionLike() && !Map.class.isAssignableFrom(typeInformation.getType());
} }
private static boolean isAnyPropertyAnnotatedAsField(java.lang.reflect.Field[] fields){ private static boolean isAnyPropertyAnnotatedAsField(java.lang.reflect.Field[] fields) {
if(fields != null){ if (fields != null) {
for(java.lang.reflect.Field field : fields){ for (java.lang.reflect.Field field : fields) {
if (field.isAnnotationPresent(Field.class)){ if (field.isAnnotationPresent(Field.class)) {
return true; return true;
} }
} }
@ -124,7 +114,7 @@ class MappingBuilder {
return false; return false;
} }
private static boolean isIdField(java.lang.reflect.Field field, String idFieldName){ private static boolean isIdField(java.lang.reflect.Field field, String idFieldName) {
return idFieldName.equals(field.getName()); return idFieldName.equals(field.getName());
} }
} }

View File

@ -20,6 +20,7 @@ import org.springframework.data.domain.Page;
/** /**
* ResultsMapper * ResultsMapper
*
* @param <T> * @param <T>
* *
* @author Rizwan Idrees * @author Rizwan Idrees

View File

@ -27,7 +27,7 @@ import org.springframework.data.mapping.context.MappingContext;
* @author Mohsin Husen * @author Mohsin Husen
*/ */
public interface ElasticsearchConverter{ public interface ElasticsearchConverter {
/** /**
* Returns the underlying {@link org.springframework.data.mapping.context.MappingContext} used by the converter. * Returns the underlying {@link org.springframework.data.mapping.context.MappingContext} used by the converter.

View File

@ -33,22 +33,23 @@ import org.springframework.util.Assert;
* @author Mohsin Husen * @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; private final GenericConversionService conversionService;
@SuppressWarnings("unused") @SuppressWarnings("unused")
private ApplicationContext applicationContext; private ApplicationContext applicationContext;
public MappingElasticsearchConverter(MappingContext<? extends ElasticsearchPersistentEntity<?>,ElasticsearchPersistentProperty> mappingContext) { public MappingElasticsearchConverter(
MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> mappingContext) {
Assert.notNull(mappingContext); Assert.notNull(mappingContext);
this.mappingContext = mappingContext; this.mappingContext = mappingContext;
this.conversionService = new DefaultConversionService(); this.conversionService = new DefaultConversionService();
} }
@Override @Override
public MappingContext<? extends ElasticsearchPersistentEntity<?>,ElasticsearchPersistentProperty> getMappingContext() { public MappingContext<? extends ElasticsearchPersistentEntity<?>, ElasticsearchPersistentProperty> getMappingContext() {
return mappingContext; return mappingContext;
} }

View File

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

View File

@ -17,6 +17,7 @@ package org.springframework.data.elasticsearch.core.mapping;
import org.springframework.core.convert.converter.Converter; import org.springframework.core.convert.converter.Converter;
import org.springframework.data.mapping.PersistentProperty; import org.springframework.data.mapping.PersistentProperty;
/** /**
* ElasticsearchPersistentProperty * ElasticsearchPersistentProperty
* *
@ -24,7 +25,7 @@ import org.springframework.data.mapping.PersistentProperty;
* @author Mohsin Husen * @author Mohsin Husen
*/ */
public interface ElasticsearchPersistentProperty extends PersistentProperty<ElasticsearchPersistentProperty>{ public interface ElasticsearchPersistentProperty extends PersistentProperty<ElasticsearchPersistentProperty> {
String getFieldName(); String getFieldName();

View File

@ -39,8 +39,8 @@ import static org.springframework.util.StringUtils.hasText;
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
*/ */
public class SimpleElasticsearchPersistentEntity<T> extends BasicPersistentEntity<T, ElasticsearchPersistentProperty> implements public class SimpleElasticsearchPersistentEntity<T> extends BasicPersistentEntity<T, ElasticsearchPersistentProperty>
ElasticsearchPersistentEntity<T>, ApplicationContextAware { implements ElasticsearchPersistentEntity<T>, ApplicationContextAware {
private final StandardEvaluationContext context; private final StandardEvaluationContext context;
private String indexName; private String indexName;
@ -54,11 +54,12 @@ public class SimpleElasticsearchPersistentEntity<T> extends BasicPersistentEntit
super(typeInformation); super(typeInformation);
this.context = new StandardEvaluationContext(); this.context = new StandardEvaluationContext();
Class<T> clazz = typeInformation.getType(); Class<T> clazz = typeInformation.getType();
if(clazz.isAnnotationPresent(Document.class)){ if (clazz.isAnnotationPresent(Document.class)) {
Document document = clazz.getAnnotation(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\")"); 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.indexName = typeInformation.getType().getAnnotation(Document.class).indexName();
this.indexType = hasText(document.type())? document.type() : clazz.getSimpleName().toLowerCase(Locale.ENGLISH); this.indexType = hasText(document.type()) ? document.type() : clazz.getSimpleName().toLowerCase(Locale.ENGLISH);
this.shards = typeInformation.getType().getAnnotation(Document.class).shards(); this.shards = typeInformation.getType().getAnnotation(Document.class).shards();
this.replicas = typeInformation.getType().getAnnotation(Document.class).replicas(); this.replicas = typeInformation.getType().getAnnotation(Document.class).replicas();
this.refreshInterval = typeInformation.getType().getAnnotation(Document.class).refreshInterval(); this.refreshInterval = typeInformation.getType().getAnnotation(Document.class).refreshInterval();
@ -106,7 +107,7 @@ public class SimpleElasticsearchPersistentEntity<T> extends BasicPersistentEntit
@Override @Override
public void addPersistentProperty(ElasticsearchPersistentProperty property) { public void addPersistentProperty(ElasticsearchPersistentProperty property) {
super.addPersistentProperty(property); super.addPersistentProperty(property);
if(property.isVersionProperty()){ if (property.isVersionProperty()) {
Assert.isTrue(property.getType() == Long.class, "Version property should be Long"); 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 Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
*/ */
public class SimpleElasticsearchPersistentProperty extends AnnotationBasedPersistentProperty<ElasticsearchPersistentProperty> implements public class SimpleElasticsearchPersistentProperty extends
ElasticsearchPersistentProperty { AnnotationBasedPersistentProperty<ElasticsearchPersistentProperty> implements ElasticsearchPersistentProperty {
private static final Set<Class<?>> SUPPORTED_ID_TYPES = new HashSet<Class<?>>(); private static final Set<Class<?>> SUPPORTED_ID_TYPES = new HashSet<Class<?>>();
private static final Set<String> SUPPORTED_ID_PROPERTY_NAMES = new HashSet<String>(); private static final Set<String> SUPPORTED_ID_PROPERTY_NAMES = new HashSet<String>();

View File

@ -30,7 +30,7 @@ import static org.apache.commons.collections.CollectionUtils.addAll;
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
*/ */
abstract class AbstractQuery implements Query{ abstract class AbstractQuery implements Query {
protected Pageable pageable = DEFAULT_PAGE; protected Pageable pageable = DEFAULT_PAGE;
protected Sort sort; protected Sort sort;
@ -56,7 +56,7 @@ abstract class AbstractQuery implements Query{
} }
@Override @Override
public void addFields(String...fields) { public void addFields(String... fields) {
addAll(this.fields, fields); addAll(this.fields, fields);
} }
@ -72,12 +72,12 @@ abstract class AbstractQuery implements Query{
@Override @Override
public void addIndices(String... indices) { public void addIndices(String... indices) {
addAll(this.indices,indices); addAll(this.indices, indices);
} }
@Override @Override
public void addTypes(String... types) { public void addTypes(String... types) {
addAll(this.types,types); addAll(this.types, types);
} }
@Override @Override

View File

@ -255,7 +255,6 @@ public class Criteria {
return this; return this;
} }
/** /**
* Crates new CriteriaEntry allowing native elasticsearch expressions * Crates new CriteriaEntry allowing native elasticsearch expressions
* *
@ -346,7 +345,6 @@ public class Criteria {
return this; return this;
} }
private void assertNoBlankInWildcardedQuery(String searchString, boolean leadingWildcard, boolean trailingWildcard) { private void assertNoBlankInWildcardedQuery(String searchString, boolean leadingWildcard, boolean trailingWildcard) {
if (StringUtils.contains(searchString, CRITERIA_VALUE_SEPERATOR)) { if (StringUtils.contains(searchString, CRITERIA_VALUE_SEPERATOR)) {
throw new InvalidDataAccessApiUsageException("Cannot constructQuery '" + (leadingWildcard ? "*" : "") + "\"" throw new InvalidDataAccessApiUsageException("Cannot constructQuery '" + (leadingWildcard ? "*" : "") + "\""
@ -384,11 +382,11 @@ public class Criteria {
return this.negating; return this.negating;
} }
public boolean isAnd(){ public boolean isAnd() {
return AND_OPERATOR == getConjunctionOperator(); return AND_OPERATOR == getConjunctionOperator();
} }
public boolean isOr(){ public boolean isOr() {
return OR_OPERATOR == getConjunctionOperator(); return OR_OPERATOR == getConjunctionOperator();
} }

View File

@ -15,7 +15,6 @@
*/ */
package org.springframework.data.elasticsearch.core.query; package org.springframework.data.elasticsearch.core.query;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.util.Assert; import org.springframework.util.Assert;
@ -25,9 +24,10 @@ import org.springframework.util.Assert;
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
*/ */
public class CriteriaQuery extends AbstractQuery{ public class CriteriaQuery extends AbstractQuery {
private Criteria criteria; private Criteria criteria;
private CriteriaQuery() { private CriteriaQuery() {
} }

View File

@ -15,15 +15,15 @@
*/ */
package org.springframework.data.elasticsearch.core.query; package org.springframework.data.elasticsearch.core.query;
import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilder;
/** /**
* DeleteQuery * DeleteQuery
* *
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
*/ */
public class DeleteQuery{ public class DeleteQuery {
private QueryBuilder query; private QueryBuilder query;

View File

@ -21,7 +21,7 @@ package org.springframework.data.elasticsearch.core.query;
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
*/ */
public class GetQuery{ public class GetQuery {
private String id; private String id;

View File

@ -22,7 +22,7 @@ package org.springframework.data.elasticsearch.core.query;
* @author Mohsin Husen * @author Mohsin Husen
*/ */
public class IndexQuery{ public class IndexQuery {
private String id; private String id;
private Object object; private Object object;

View File

@ -78,7 +78,7 @@ public class MoreLikeThisQuery {
return searchIndices; return searchIndices;
} }
public void addSearchIndices(String...searchIndices) { public void addSearchIndices(String... searchIndices) {
addAll(this.searchIndices, searchIndices); addAll(this.searchIndices, searchIndices);
} }
@ -86,7 +86,7 @@ public class MoreLikeThisQuery {
return searchTypes; return searchTypes;
} }
public void addSearchTypes(String...searchTypes) { public void addSearchTypes(String... searchTypes) {
addAll(this.searchTypes, searchTypes); addAll(this.searchTypes, searchTypes);
} }
@ -94,8 +94,8 @@ public class MoreLikeThisQuery {
return fields; return fields;
} }
public void addFields(String...fields) { public void addFields(String... fields) {
addAll(this.fields,fields); addAll(this.fields, fields);
} }
public String getRouting() { public String getRouting() {
@ -134,8 +134,8 @@ public class MoreLikeThisQuery {
return stopWords; return stopWords;
} }
public void addStopWords(String...stopWords) { public void addStopWords(String... stopWords) {
addAll(this.stopWords,stopWords); addAll(this.stopWords, stopWords);
} }
public Integer getMinDocFreq() { public Integer getMinDocFreq() {

View File

@ -15,7 +15,6 @@
*/ */
package org.springframework.data.elasticsearch.core.query; package org.springframework.data.elasticsearch.core.query;
import org.elasticsearch.index.query.FilterBuilder; import org.elasticsearch.index.query.FilterBuilder;
import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.sort.SortBuilder; import org.elasticsearch.search.sort.SortBuilder;
@ -43,7 +42,6 @@ public class NativeSearchQuery extends AbstractQuery implements SearchQuery {
return query; return query;
} }
public FilterBuilder getFilter() { public FilterBuilder getFilter() {
return filter; return filter;
} }

View File

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

View File

@ -15,12 +15,12 @@
*/ */
package org.springframework.data.elasticsearch.core.query; package org.springframework.data.elasticsearch.core.query;
import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import java.util.List; import java.util.List;
/** /**
* Query * Query
* *
@ -32,7 +32,6 @@ public interface Query {
public static final int DEFAULT_PAGE_SIZE = 10; public static final int DEFAULT_PAGE_SIZE = 10;
public static final Pageable DEFAULT_PAGE = new PageRequest(0, DEFAULT_PAGE_SIZE); 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 * restrict result to entries on given page. Corresponds to the 'start' and 'rows' parameter in elasticsearch
* *
@ -41,14 +40,12 @@ public interface Query {
*/ */
<T extends Query> T setPageable(Pageable pageable); <T extends Query> T setPageable(Pageable pageable);
/** /**
* Get filter queries if defined * Get filter queries if defined
* *
* @return * @return
*/ */
//List<FilterQuery> getFilterQueries(); // List<FilterQuery> getFilterQueries();
/** /**
* Get page settings if defined * Get page settings if defined
@ -57,8 +54,6 @@ public interface Query {
*/ */
Pageable getPageable(); Pageable getPageable();
/** /**
* Add {@link org.springframework.data.domain.Sort} to query * Add {@link org.springframework.data.domain.Sort} to query
* *
@ -72,41 +67,44 @@ public interface Query {
*/ */
Sort getSort(); Sort getSort();
/** /**
* Get Indices to be searched * Get Indices to be searched
*
* @return * @return
*/ */
List<String> getIndices(); List<String> getIndices();
/** /**
* Add Indices to be added as part of search request * Add Indices to be added as part of search request
*
* @param indices * @param indices
*/ */
void addIndices(String...indices); void addIndices(String... indices);
/** /**
* Add types to be searched * Add types to be searched
*
* @param types * @param types
*/ */
void addTypes(String...types); void addTypes(String... types);
/** /**
* Get types to be searched * Get types to be searched
*
* @return * @return
*/ */
List<String> getTypes(); List<String> getTypes();
/** /**
* Add fields to be added as part of search request * Add fields to be added as part of search request
*
* @param fields * @param fields
*/ */
void addFields(String...fields); void addFields(String... fields);
/** /**
* Get fields to be returned as part of search request * Get fields to be returned as part of search request
*
* @return * @return
*/ */
List<String> getFields(); 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.FilterBuilder;
import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.sort.SortBuilder; import org.elasticsearch.search.sort.SortBuilder;
/** /**
* NativeSearchQuery * NativeSearchQuery
* *
@ -27,6 +28,8 @@ import org.elasticsearch.search.sort.SortBuilder;
*/ */
public interface SearchQuery extends Query { public interface SearchQuery extends Query {
QueryBuilder getQuery(); QueryBuilder getQuery();
FilterBuilder getFilter(); FilterBuilder getFilter();
SortBuilder getElasticsearchSort(); SortBuilder getElasticsearchSort();
} }

View File

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

View File

@ -31,7 +31,7 @@ import java.io.Serializable;
* @author Mohsin Husen * @author Mohsin Husen
*/ */
@NoRepositoryBean @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);

View File

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

View File

@ -64,7 +64,8 @@ public class ElasticsearchRepositoryExtension extends CdiRepositoryExtensionSupp
} }
private <T> Bean<T> createRepositoryBean(Class<T> repositoryType, Set<Annotation> qualifiers, BeanManager beanManager) { 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) { if (elasticsearchOperationsBean == null) {
throw new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.", throw new UnsatisfiedResolutionException(String.format("Unable to resolve a bean for '%s' with qualifiers %s.",

View File

@ -21,8 +21,8 @@ import org.springframework.data.repository.config.RepositoryConfigurationExtensi
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
/** /**
* {@link org.springframework.context.annotation.ImportBeanDefinitionRegistrar} implementation to trigger configuration of the {@link EnableElasticsearchRepositories} * {@link org.springframework.context.annotation.ImportBeanDefinitionRegistrar} implementation to trigger configuration
* annotation. * of the {@link EnableElasticsearchRepositories} annotation.
* *
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @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.springframework.data.repository.config.XmlRepositoryConfigurationSource;
import org.w3c.dom.Element; import org.w3c.dom.Element;
/** /**
* {@link org.springframework.data.repository.config.RepositoryConfigurationExtension} implementation to configure Elasticsearch repository configuration support, * {@link org.springframework.data.repository.config.RepositoryConfigurationExtension} implementation to configure
* evaluating the {@link EnableElasticsearchRepositories} annotation or the equivalent XML element. * Elasticsearch repository configuration support, evaluating the {@link EnableElasticsearchRepositories} annotation or
* the equivalent XML element.
* *
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen

View File

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

View File

@ -31,7 +31,8 @@ public abstract class AbstractElasticsearchRepositoryQuery implements Repository
protected ElasticsearchQueryMethod queryMethod; protected ElasticsearchQueryMethod queryMethod;
protected ElasticsearchOperations elasticsearchOperations; protected ElasticsearchOperations elasticsearchOperations;
public AbstractElasticsearchRepositoryQuery(ElasticsearchQueryMethod queryMethod, ElasticsearchOperations elasticsearchOperations) { public AbstractElasticsearchRepositoryQuery(ElasticsearchQueryMethod queryMethod,
ElasticsearchOperations elasticsearchOperations) {
this.queryMethod = queryMethod; this.queryMethod = queryMethod;
this.elasticsearchOperations = elasticsearchOperations; this.elasticsearchOperations = elasticsearchOperations;
} }

View File

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

View File

@ -36,9 +36,11 @@ public class ElasticsearchQueryMethod extends QueryMethod {
private final ElasticsearchEntityInformation<?, ?> entityInformation; private final ElasticsearchEntityInformation<?, ?> entityInformation;
private Method method; private Method method;
public ElasticsearchQueryMethod(Method method, RepositoryMetadata metadata, ElasticsearchEntityInformationCreator elasticsearchEntityInformationCreator) { public ElasticsearchQueryMethod(Method method, RepositoryMetadata metadata,
ElasticsearchEntityInformationCreator elasticsearchEntityInformationCreator) {
super(method, metadata); super(method, metadata);
this.entityInformation = elasticsearchEntityInformationCreator.getEntityInformation(metadata.getReturnedDomainClass(method)); this.entityInformation = elasticsearchEntityInformationCreator.getEntityInformation(metadata
.getReturnedDomainClass(method));
this.method = method; this.method = method;
} }

View File

@ -15,7 +15,6 @@
*/ */
package org.springframework.data.elasticsearch.repository.query; package org.springframework.data.elasticsearch.repository.query;
import org.springframework.core.convert.support.GenericConversionService; import org.springframework.core.convert.support.GenericConversionService;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.data.elasticsearch.core.convert.DateTimeConverters; import org.springframework.data.elasticsearch.core.convert.DateTimeConverters;
@ -32,7 +31,7 @@ import java.util.regex.Pattern;
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
*/ */
public class ElasticsearchStringQuery extends AbstractElasticsearchRepositoryQuery{ public class ElasticsearchStringQuery extends AbstractElasticsearchRepositoryQuery {
private static final Pattern PARAMETER_PLACEHOLDER = Pattern.compile("\\?(\\d+)"); private static final Pattern PARAMETER_PLACEHOLDER = Pattern.compile("\\?(\\d+)");
private String query; private String query;
@ -52,7 +51,8 @@ public class ElasticsearchStringQuery extends AbstractElasticsearchRepositoryQue
} }
public ElasticsearchStringQuery(ElasticsearchQueryMethod queryMethod, ElasticsearchOperations elasticsearchOperations, String query) { public ElasticsearchStringQuery(ElasticsearchQueryMethod queryMethod,
ElasticsearchOperations elasticsearchOperations, String query) {
super(queryMethod, elasticsearchOperations); super(queryMethod, elasticsearchOperations);
Assert.notNull(query, "Query cannot be empty"); Assert.notNull(query, "Query cannot be empty");
this.query = query; this.query = query;
@ -62,20 +62,19 @@ public class ElasticsearchStringQuery extends AbstractElasticsearchRepositoryQue
public Object execute(Object[] parameters) { public Object execute(Object[] parameters) {
ParametersParameterAccessor accessor = new ParametersParameterAccessor(queryMethod.getParameters(), parameters); ParametersParameterAccessor accessor = new ParametersParameterAccessor(queryMethod.getParameters(), parameters);
StringQuery stringQuery = createQuery(accessor); StringQuery stringQuery = createQuery(accessor);
if(queryMethod.isPageQuery()){ if (queryMethod.isPageQuery()) {
stringQuery.setPageable(accessor.getPageable()); stringQuery.setPageable(accessor.getPageable());
return elasticsearchOperations.queryForPage(stringQuery, queryMethod.getEntityInformation().getJavaType()); return elasticsearchOperations.queryForPage(stringQuery, queryMethod.getEntityInformation().getJavaType());
} else if(queryMethod.isCollectionQuery()) { } else if (queryMethod.isCollectionQuery()) {
if(accessor.getPageable() != null) { if (accessor.getPageable() != null) {
stringQuery.setPageable(accessor.getPageable()); stringQuery.setPageable(accessor.getPageable());
} }
return elasticsearchOperations.queryForList(stringQuery,queryMethod.getEntityInformation().getJavaType()); 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) { protected StringQuery createQuery(ParametersParameterAccessor parameterAccessor) {
String queryString = replacePlaceholders(this.query, parameterAccessor); String queryString = replacePlaceholders(this.query, parameterAccessor);
return new StringQuery(queryString); return new StringQuery(queryString);

View File

@ -15,7 +15,6 @@
*/ */
package org.springframework.data.elasticsearch.repository.query.parser; package org.springframework.data.elasticsearch.repository.query.parser;
import org.springframework.dao.InvalidDataAccessApiUsageException; import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort;
import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty; import org.springframework.data.elasticsearch.core.mapping.ElasticsearchPersistentProperty;
@ -37,11 +36,12 @@ import java.util.Iterator;
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @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) { public ElasticsearchQueryCreator(PartTree tree, ParameterAccessor parameters,
MappingContext<?, ElasticsearchPersistentProperty> context) {
super(tree, parameters); super(tree, parameters);
this.context = context; this.context = context;
} }
@ -53,7 +53,8 @@ public class ElasticsearchQueryCreator extends AbstractQueryCreator<CriteriaQuer
@Override @Override
protected CriteriaQuery create(Part part, Iterator<Object> iterator) { protected CriteriaQuery create(Part part, Iterator<Object> iterator) {
PersistentPropertyPath<ElasticsearchPersistentProperty> path = context.getPersistentPropertyPath(part.getProperty()); PersistentPropertyPath<ElasticsearchPersistentProperty> path = context
.getPersistentPropertyPath(part.getProperty());
return new CriteriaQuery(from(part.getType(), return new CriteriaQuery(from(part.getType(),
new Criteria(path.toDotPath(ElasticsearchPersistentProperty.PropertyToFieldNameConverter.INSTANCE)), iterator)); new Criteria(path.toDotPath(ElasticsearchPersistentProperty.PropertyToFieldNameConverter.INSTANCE)), iterator));
} }
@ -63,7 +64,8 @@ public class ElasticsearchQueryCreator extends AbstractQueryCreator<CriteriaQuer
if (base == null) { if (base == null) {
return create(part, iterator); return create(part, iterator);
} }
PersistentPropertyPath<ElasticsearchPersistentProperty> path = context.getPersistentPropertyPath(part.getProperty()); PersistentPropertyPath<ElasticsearchPersistentProperty> path = context
.getPersistentPropertyPath(part.getProperty());
return base.addCriteria(from(part.getType(), return base.addCriteria(from(part.getType(),
new Criteria(path.toDotPath(ElasticsearchPersistentProperty.PropertyToFieldNameConverter.INSTANCE)), iterator)); new Criteria(path.toDotPath(ElasticsearchPersistentProperty.PropertyToFieldNameConverter.INSTANCE)), iterator));
} }
@ -81,7 +83,6 @@ public class ElasticsearchQueryCreator extends AbstractQueryCreator<CriteriaQuer
return query.addSort(sort); return query.addSort(sort);
} }
private Criteria from(Part.Type type, Criteria instance, Iterator<?> parameters) { private Criteria from(Part.Type type, Criteria instance, Iterator<?> parameters) {
Criteria criteria = instance; Criteria criteria = instance;
if (criteria == null) { if (criteria == null) {

View File

@ -36,15 +36,16 @@ import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.springframework.data.elasticsearch.core.query.Query.DEFAULT_PAGE; 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 Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
* @author Ryan Henszey * @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 ElasticsearchOperations elasticsearchOperations;
protected Class<T> entityClass; protected Class<T> entityClass;
@ -58,7 +59,8 @@ public abstract class AbstractElasticsearchRepository<T,ID extends Serializable>
this.setElasticsearchOperations(elasticsearchOperations); this.setElasticsearchOperations(elasticsearchOperations);
} }
public AbstractElasticsearchRepository(ElasticsearchEntityInformation<T, ID> metadata, ElasticsearchOperations elasticsearchOperations) { public AbstractElasticsearchRepository(ElasticsearchEntityInformation<T, ID> metadata,
ElasticsearchOperations elasticsearchOperations) {
this(elasticsearchOperations); this(elasticsearchOperations);
Assert.notNull(metadata); Assert.notNull(metadata);
this.entityInformation = metadata; this.entityInformation = metadata;
@ -67,11 +69,11 @@ public abstract class AbstractElasticsearchRepository<T,ID extends Serializable>
putMapping(); putMapping();
} }
private void createIndex(){ private void createIndex() {
elasticsearchOperations.createIndex(getEntityClass()); elasticsearchOperations.createIndex(getEntityClass());
} }
private void putMapping(){ private void putMapping() {
elasticsearchOperations.putMapping(getEntityClass()); elasticsearchOperations.putMapping(getEntityClass());
} }
@ -93,10 +95,7 @@ public abstract class AbstractElasticsearchRepository<T,ID extends Serializable>
@Override @Override
public Page<T> findAll(Pageable pageable) { public Page<T> findAll(Pageable pageable) {
SearchQuery query = new NativeSearchQueryBuilder() SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withPageable(pageable).build();
.withQuery(matchAllQuery())
.withPageable(pageable)
.build();
return elasticsearchOperations.queryForPage(query, getEntityClass()); return elasticsearchOperations.queryForPage(query, getEntityClass());
} }
@ -106,26 +105,22 @@ public abstract class AbstractElasticsearchRepository<T,ID extends Serializable>
if (itemCount == 0) { if (itemCount == 0) {
return new PageImpl<T>(Collections.<T> emptyList()); return new PageImpl<T>(Collections.<T> emptyList());
} }
SearchQuery query = new NativeSearchQueryBuilder() SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withQuery(matchAllQuery()) .withPageable(new PageRequest(0, itemCount, sort)).build();
.withPageable(new PageRequest(0,itemCount, sort))
.build();
return elasticsearchOperations.queryForPage(query, getEntityClass()); return elasticsearchOperations.queryForPage(query, getEntityClass());
} }
@Override @Override
public Iterable<T> findAll(Iterable<ID> ids) { public Iterable<T> findAll(Iterable<ID> ids) {
SearchQuery query = new NativeSearchQueryBuilder() SearchQuery query = new NativeSearchQueryBuilder().withQuery(inQuery(entityInformation.getIdAttribute(), ids))
.withQuery(inQuery(entityInformation.getIdAttribute(), ids))
.build(); .build();
return elasticsearchOperations.queryForPage(query, getEntityClass()); return elasticsearchOperations.queryForPage(query, getEntityClass());
} }
@Override @Override
public long count() { public long count() {
SearchQuery query = new NativeSearchQueryBuilder() SearchQuery query = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
.withQuery(matchAllQuery()).build(); return elasticsearchOperations.count(query, getEntityClass());
return elasticsearchOperations.count(query,getEntityClass());
} }
@Override @Override
@ -138,9 +133,9 @@ public abstract class AbstractElasticsearchRepository<T,ID extends Serializable>
public <S extends T> List<S> save(List<S> entities) { public <S extends T> List<S> save(List<S> entities) {
Assert.notNull(entities, "Cannot insert 'null' as a List."); Assert.notNull(entities, "Cannot insert 'null' as a List.");
Assert.notEmpty(entities,"Cannot insert empty List."); Assert.notEmpty(entities, "Cannot insert empty List.");
List<IndexQuery> queries = new ArrayList<IndexQuery>(); List<IndexQuery> queries = new ArrayList<IndexQuery>();
for(S s:entities){ for (S s : entities) {
queries.add(createIndexQuery(s)); queries.add(createIndexQuery(s));
} }
elasticsearchOperations.bulkIndex(queries); elasticsearchOperations.bulkIndex(queries);
@ -160,7 +155,7 @@ public abstract class AbstractElasticsearchRepository<T,ID extends Serializable>
throw new InvalidDataAccessApiUsageException("Entities have to be inside a collection"); throw new InvalidDataAccessApiUsageException("Entities have to be inside a collection");
} }
List<IndexQuery> queries = new ArrayList<IndexQuery>(); List<IndexQuery> queries = new ArrayList<IndexQuery>();
for(S s: entities){ for (S s : entities) {
queries.add(createIndexQuery(s)); queries.add(createIndexQuery(s));
} }
elasticsearchOperations.bulkIndex(queries); elasticsearchOperations.bulkIndex(queries);
@ -175,11 +170,10 @@ public abstract class AbstractElasticsearchRepository<T,ID extends Serializable>
@Override @Override
public Iterable<T> search(QueryBuilder query) { public Iterable<T> search(QueryBuilder query) {
SearchQuery searchQuery = new NativeSearchQueryBuilder() SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(query).build();
.withQuery(query).build();
int count = (int) elasticsearchOperations.count(searchQuery, getEntityClass()); int count = (int) elasticsearchOperations.count(searchQuery, getEntityClass());
if(count == 0){ if (count == 0) {
return new PageImpl<T>(Collections.<T>emptyList()); return new PageImpl<T>(Collections.<T> emptyList());
} }
searchQuery.setPageable(new PageRequest(0, count)); searchQuery.setPageable(new PageRequest(0, count));
return elasticsearchOperations.queryForPage(searchQuery, getEntityClass()); return elasticsearchOperations.queryForPage(searchQuery, getEntityClass());
@ -187,15 +181,12 @@ public abstract class AbstractElasticsearchRepository<T,ID extends Serializable>
@Override @Override
public Page<T> search(QueryBuilder query, Pageable pageable) { public Page<T> search(QueryBuilder query, Pageable pageable) {
SearchQuery searchQuery = new NativeSearchQueryBuilder() SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(query).withPageable(pageable).build();
.withQuery(query)
.withPageable(pageable)
.build();
return elasticsearchOperations.queryForPage(searchQuery, getEntityClass()); return elasticsearchOperations.queryForPage(searchQuery, getEntityClass());
} }
@Override @Override
public Page<T> search(SearchQuery query){ public Page<T> search(SearchQuery query) {
return elasticsearchOperations.queryForPage(query, getEntityClass()); return elasticsearchOperations.queryForPage(query, getEntityClass());
} }
@ -207,21 +198,21 @@ public abstract class AbstractElasticsearchRepository<T,ID extends Serializable>
query.setId(stringIdRepresentation(extractIdFromBean(entity))); query.setId(stringIdRepresentation(extractIdFromBean(entity)));
query.setPageable(searchQuery.getPageable() != null ? searchQuery.getPageable() : DEFAULT_PAGE); query.setPageable(searchQuery.getPageable() != null ? searchQuery.getPageable() : DEFAULT_PAGE);
query.addFields(searchQuery.getFields().toArray(new String[searchQuery.getFields().size()])); query.addFields(searchQuery.getFields().toArray(new String[searchQuery.getFields().size()]));
if(!searchQuery.getIndices().isEmpty()) { if (!searchQuery.getIndices().isEmpty()) {
query.addSearchIndices(searchQuery.getIndices().toArray(new String[searchQuery.getIndices().size()])); query.addSearchIndices(searchQuery.getIndices().toArray(new String[searchQuery.getIndices().size()]));
} }
if(!searchQuery.getTypes().isEmpty()){ if (!searchQuery.getTypes().isEmpty()) {
query.addSearchTypes(searchQuery.getTypes().toArray(new String[searchQuery.getTypes().size()])); query.addSearchTypes(searchQuery.getTypes().toArray(new String[searchQuery.getTypes().size()]));
} }
return elasticsearchOperations.moreLikeThis(query, getEntityClass()); return elasticsearchOperations.moreLikeThis(query, getEntityClass());
} }
@Override @Override
public void delete(ID id) { public void delete(ID id) {
Assert.notNull(id, "Cannot delete entity with id 'null'."); Assert.notNull(id, "Cannot delete entity with id 'null'.");
elasticsearchOperations.delete(entityInformation.getIndexName(), entityInformation.getType(),stringIdRepresentation(id)); elasticsearchOperations.delete(entityInformation.getIndexName(), entityInformation.getType(),
elasticsearchOperations.refresh(entityInformation.getIndexName(),true); stringIdRepresentation(id));
elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
} }
@Override @Override
@ -244,10 +235,10 @@ public abstract class AbstractElasticsearchRepository<T,ID extends Serializable>
DeleteQuery deleteQuery = new DeleteQuery(); DeleteQuery deleteQuery = new DeleteQuery();
deleteQuery.setQuery(matchAllQuery()); deleteQuery.setQuery(matchAllQuery());
elasticsearchOperations.delete(deleteQuery, getEntityClass()); elasticsearchOperations.delete(deleteQuery, getEntityClass());
elasticsearchOperations.refresh(entityInformation.getIndexName(),true); elasticsearchOperations.refresh(entityInformation.getIndexName(), true);
} }
private IndexQuery createIndexQuery(T entity){ private IndexQuery createIndexQuery(T entity) {
IndexQuery query = new IndexQuery(); IndexQuery query = new IndexQuery();
query.setObject(entity); query.setObject(entity);
query.setId(stringIdRepresentation(extractIdFromBean(entity))); query.setId(stringIdRepresentation(extractIdFromBean(entity)));
@ -298,7 +289,6 @@ public abstract class AbstractElasticsearchRepository<T,ID extends Serializable>
this.elasticsearchOperations = elasticsearchOperations; this.elasticsearchOperations = elasticsearchOperations;
} }
protected ID extractIdFromBean(T entity) { protected ID extractIdFromBean(T entity) {
if (entityInformation != null) { if (entityInformation != null) {
return entityInformation.getId(entity); return entityInformation.getId(entity);
@ -308,7 +298,7 @@ public abstract class AbstractElasticsearchRepository<T,ID extends Serializable>
protected abstract String stringIdRepresentation(ID id); protected abstract String stringIdRepresentation(ID id);
private Long extractVersionFromBean(T entity){ private Long extractVersionFromBean(T entity) {
if (entityInformation != null) { if (entityInformation != null) {
return entityInformation.getVersion(entity); return entityInformation.getVersion(entity);
} }

View File

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

View File

@ -42,15 +42,14 @@ import org.springframework.util.Assert;
*/ */
public class ElasticsearchRepositoryFactory extends RepositoryFactorySupport { public class ElasticsearchRepositoryFactory extends RepositoryFactorySupport {
private final ElasticsearchOperations elasticsearchOperations; private final ElasticsearchOperations elasticsearchOperations;
private final ElasticsearchEntityInformationCreator entityInformationCreator; private final ElasticsearchEntityInformationCreator entityInformationCreator;
public ElasticsearchRepositoryFactory(ElasticsearchOperations elasticsearchOperations) { public ElasticsearchRepositoryFactory(ElasticsearchOperations elasticsearchOperations) {
Assert.notNull(elasticsearchOperations); Assert.notNull(elasticsearchOperations);
this.elasticsearchOperations = elasticsearchOperations; this.elasticsearchOperations = elasticsearchOperations;
this.entityInformationCreator = new ElasticsearchEntityInformationCreatorImpl(elasticsearchOperations.getElasticsearchConverter() this.entityInformationCreator = new ElasticsearchEntityInformationCreatorImpl(elasticsearchOperations
.getMappingContext()); .getElasticsearchConverter().getMappingContext());
} }
@Override @Override
@ -66,18 +65,17 @@ public class ElasticsearchRepositoryFactory extends RepositoryFactorySupport {
AbstractElasticsearchRepository repository; AbstractElasticsearchRepository repository;
//Probably a better way to store and look these up. // Probably a better way to store and look these up.
if(Integer.class.isAssignableFrom(entityInformation.getIdType()) || if (Integer.class.isAssignableFrom(entityInformation.getIdType())
Long.class.isAssignableFrom(entityInformation.getIdType()) || || Long.class.isAssignableFrom(entityInformation.getIdType())
Double.class.isAssignableFrom(entityInformation.getIdType())){ || Double.class.isAssignableFrom(entityInformation.getIdType())) {
//logger.debug("Using NumberKeyedRepository for " + metadata.getRepositoryInterface()); // logger.debug("Using NumberKeyedRepository for " + metadata.getRepositoryInterface());
repository = new NumberKeyedRepository(getEntityInformation(metadata.getDomainType()), elasticsearchOperations); repository = new NumberKeyedRepository(getEntityInformation(metadata.getDomainType()), elasticsearchOperations);
} } else if (entityInformation.getIdType() == String.class) {
else if (entityInformation.getIdType() == String.class){ // logger.debug("Using SimpleElasticsearchRepository for " + metadata.getRepositoryInterface());
//logger.debug("Using SimpleElasticsearchRepository for " + metadata.getRepositoryInterface()); repository = new SimpleElasticsearchRepository(getEntityInformation(metadata.getDomainType()),
repository = new SimpleElasticsearchRepository(getEntityInformation(metadata.getDomainType()), elasticsearchOperations); elasticsearchOperations);
} } else {
else {
throw new IllegalArgumentException("Unsuppored ID type " + entityInformation.getIdType()); throw new IllegalArgumentException("Unsuppored ID type " + entityInformation.getIdType());
} }
repository.setEntityClass(metadata.getDomainType()); repository.setEntityClass(metadata.getDomainType());
@ -113,8 +111,7 @@ public class ElasticsearchRepositoryFactory extends RepositoryFactorySupport {
if (namedQueries.hasQuery(namedQueryName)) { if (namedQueries.hasQuery(namedQueryName)) {
String namedQuery = namedQueries.getQuery(namedQueryName); String namedQuery = namedQueries.getQuery(namedQueryName);
return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, namedQuery); return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, namedQuery);
} } else if (queryMethod.hasAnnotatedQuery()) {
else if (queryMethod.hasAnnotatedQuery()) {
return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, queryMethod.getAnnotatedQuery()); return new ElasticsearchStringQuery(queryMethod, elasticsearchOperations, queryMethod.getAnnotatedQuery());
} }
return new ElasticsearchPartQuery(queryMethod, elasticsearchOperations); return new ElasticsearchPartQuery(queryMethod, elasticsearchOperations);

View File

@ -24,7 +24,8 @@ import org.springframework.util.Assert;
import java.io.Serializable; 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 Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
@ -54,7 +55,6 @@ public class ElasticsearchRepositoryFactoryBean<T extends Repository<S, ID>, S,
Assert.notNull(operations, "ElasticsearchOperations must be configured!"); Assert.notNull(operations, "ElasticsearchOperations must be configured!");
} }
@Override @Override
protected RepositoryFactorySupport createRepositoryFactory() { protected RepositoryFactorySupport createRepositoryFactory() {
return new ElasticsearchRepositoryFactory(operations); return new ElasticsearchRepositoryFactory(operations);

View File

@ -26,7 +26,8 @@ import org.springframework.data.repository.core.support.AbstractEntityInformatio
import org.springframework.util.Assert; 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 <T>
* @param <ID> * @param <ID>
@ -70,30 +71,32 @@ public class MappingElasticsearchEntityInformation<T, ID extends Serializable> e
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked")
@Override @Override
public Class<ID> getIdType() { public Class<ID> getIdType() {
return (Class<ID>)idClass; return (Class<ID>) idClass;
} }
@Override @Override
public String getIdAttribute() { 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' "); 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(); return entityMetadata.getIdProperty().getFieldName();
} }
@Override @Override
public String getIndexName() { public String getIndexName() {
return indexName != null? indexName : entityMetadata.getIndexName(); return indexName != null ? indexName : entityMetadata.getIndexName();
} }
@Override @Override
public String getType() { public String getType() {
return type != null? type : entityMetadata.getIndexType(); return type != null ? type : entityMetadata.getIndexType();
} }
@Override @Override
public Long getVersion(T entity) { public Long getVersion(T entity) {
ElasticsearchPersistentProperty versionProperty = entityMetadata.getVersionProperty(); ElasticsearchPersistentProperty versionProperty = entityMetadata.getVersionProperty();
try { try {
if(versionProperty != null){ if (versionProperty != null) {
return (Long) BeanWrapper.create(entity, null).getProperty(versionProperty); return (Long) BeanWrapper.create(entity, null).getProperty(versionProperty);
} }
} catch (Exception e) { } catch (Exception e) {
@ -102,5 +105,3 @@ public class MappingElasticsearchEntityInformation<T, ID extends Serializable> e
return null; return null;
} }
} }

View File

@ -18,21 +18,22 @@ package org.springframework.data.elasticsearch.repository.support;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; 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 Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
* @author Ryan Henszey * @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() { public NumberKeyedRepository() {
super(); super();
} }
public NumberKeyedRepository(ElasticsearchEntityInformation<T, ID> metadata,ElasticsearchOperations elasticsearchOperations) { public NumberKeyedRepository(ElasticsearchEntityInformation<T, ID> metadata,
ElasticsearchOperations elasticsearchOperations) {
super(metadata, elasticsearchOperations); super(metadata, elasticsearchOperations);
} }
@ -40,12 +41,9 @@ public class NumberKeyedRepository<T,ID extends Number> extends AbstractElastics
super(elasticsearchOperations); super(elasticsearchOperations);
} }
@Override @Override
protected String stringIdRepresentation(ID id) { protected String stringIdRepresentation(ID id) {
return String.valueOf(id); return String.valueOf(id);
} }
} }

View File

@ -18,20 +18,22 @@ package org.springframework.data.elasticsearch.repository.support;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations; 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 Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
* @author Ryan Henszey * @author Ryan Henszey
*/ */
public class SimpleElasticsearchRepository<T> extends AbstractElasticsearchRepository<T,String> { public class SimpleElasticsearchRepository<T> extends AbstractElasticsearchRepository<T, String> {
public SimpleElasticsearchRepository() { public SimpleElasticsearchRepository() {
super(); super();
} }
public SimpleElasticsearchRepository(ElasticsearchEntityInformation<T, String> metadata,ElasticsearchOperations elasticsearchOperations) { public SimpleElasticsearchRepository(ElasticsearchEntityInformation<T, String> metadata,
ElasticsearchOperations elasticsearchOperations) {
super(metadata, elasticsearchOperations); super(metadata, elasticsearchOperations);
} }

View File

@ -14,6 +14,7 @@
* limitations under the License. * limitations under the License.
*/ */
package org.springframework.data.elasticsearch; package org.springframework.data.elasticsearch;
/** /**
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen

View File

@ -17,11 +17,12 @@ package org.springframework.data.elasticsearch;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
/** /**
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @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 { public class Book {
@Id @Id

View File

@ -24,7 +24,7 @@ import org.springframework.data.elasticsearch.annotations.Document;
* @author Mohsin Husen * @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 { public class DoubleIDEntity {
@Id @Id
@ -66,6 +66,4 @@ public class DoubleIDEntity {
this.version = version; this.version = version;
} }
} }

View File

@ -24,10 +24,9 @@ import org.springframework.data.elasticsearch.annotations.Document;
* @author Mohsin Husen * @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 { public class IntegerIDEntity {
@Id @Id
private Integer id; private Integer id;
private String type; private String type;
@ -67,6 +66,4 @@ public class IntegerIDEntity {
this.version = version; this.version = version;
} }
} }

View File

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

View File

@ -15,8 +15,8 @@
*/ */
package org.springframework.data.elasticsearch; package org.springframework.data.elasticsearch;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
/** /**
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen

View File

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

View File

@ -25,7 +25,7 @@ import org.springframework.data.elasticsearch.annotations.Document;
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @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 { public class SampleEntity {
@Id @Id
@ -94,24 +94,13 @@ public class SampleEntity {
return true; return true;
} }
SampleEntity rhs = (SampleEntity) obj; SampleEntity rhs = (SampleEntity) obj;
return new EqualsBuilder().append(this.id, rhs.id) return new EqualsBuilder().append(this.id, rhs.id).append(this.type, rhs.type).append(this.message, rhs.message)
.append(this.type, rhs.type) .append(this.rate, rhs.rate).append(this.available, rhs.available).append(this.version, rhs.version).isEquals();
.append(this.message, rhs.message)
.append(this.rate,rhs.rate)
.append(this.available,rhs.available)
.append(this.version,rhs.version)
.isEquals();
} }
@Override @Override
public int hashCode() { public int hashCode() {
return new HashCodeBuilder() return new HashCodeBuilder().append(id).append(type).append(message).append(rate).append(available).append(version)
.append(id)
.append(type)
.append(message)
.append(rate)
.append(available)
.append(version)
.toHashCode(); .toHashCode();
} }
} }

View File

@ -15,7 +15,6 @@
*/ */
package org.springframework.data.elasticsearch; package org.springframework.data.elasticsearch;
import org.springframework.data.annotation.Id; import org.springframework.data.annotation.Id;
import org.springframework.data.elasticsearch.annotations.Document; import org.springframework.data.elasticsearch.annotations.Document;
import org.springframework.data.elasticsearch.annotations.Field; import org.springframework.data.elasticsearch.annotations.Field;
@ -24,7 +23,7 @@ import org.springframework.data.elasticsearch.annotations.Field;
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @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 { public class SampleMappingEntity {
@Id @Id
@ -50,8 +49,7 @@ public class SampleMappingEntity {
this.message = message; this.message = message;
} }
static class NestedEntity {
static class NestedEntity{
@Field(type = "string") @Field(type = "string")
private String someField; private String someField;
@ -65,6 +63,3 @@ public class SampleMappingEntity {
} }
} }

View File

@ -55,9 +55,10 @@ public class ElasticsearchNamespaceHandlerTests {
} }
@Test @Test
public void shouldCreateRepository(){ public void shouldCreateRepository() {
assertThat(context.getBean(TransportClientFactoryBean.class), is(notNullValue())); assertThat(context.getBean(TransportClientFactoryBean.class), is(notNullValue()));
assertThat(context.getBean(SampleElasticsearchRepository.class), is(instanceOf(SampleElasticsearchRepository.class))); assertThat(context.getBean(SampleElasticsearchRepository.class),
is(instanceOf(SampleElasticsearchRepository.class)));
} }
} }

View File

@ -15,7 +15,6 @@
*/ */
package org.springframework.data.elasticsearch.config; package org.springframework.data.elasticsearch.config;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;

View File

@ -15,7 +15,6 @@
*/ */
package org.springframework.data.elasticsearch.core; package org.springframework.data.elasticsearch.core;
import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.sort.FieldSortBuilder; import org.elasticsearch.search.sort.FieldSortBuilder;
@ -45,6 +44,7 @@ import static org.elasticsearch.index.query.QueryBuilders.fieldQuery;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
/** /**
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
@ -57,17 +57,17 @@ public class ElasticsearchTemplateTests {
private ElasticsearchTemplate elasticsearchTemplate; private ElasticsearchTemplate elasticsearchTemplate;
@Before @Before
public void before(){ public void before() {
elasticsearchTemplate.createIndex(SampleEntity.class); elasticsearchTemplate.createIndex(SampleEntity.class);
DeleteQuery deleteQuery = new DeleteQuery(); DeleteQuery deleteQuery = new DeleteQuery();
deleteQuery.setQuery(matchAllQuery()); deleteQuery.setQuery(matchAllQuery());
elasticsearchTemplate.delete(deleteQuery,SampleEntity.class); elasticsearchTemplate.delete(deleteQuery, SampleEntity.class);
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
} }
@Test @Test
public void shouldReturnCountForGivenSearchQuery(){ public void shouldReturnCountForGivenSearchQuery() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -79,15 +79,15 @@ public class ElasticsearchTemplateTests {
elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
//when // when
long count = elasticsearchTemplate.count(searchQuery, SampleEntity.class); long count = elasticsearchTemplate.count(searchQuery, SampleEntity.class);
//then // then
assertThat(count, is(equalTo(1L))); assertThat(count, is(equalTo(1L)));
} }
@Test @Test
public void shouldReturnObjectForGivenId(){ public void shouldReturnObjectForGivenId() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -99,18 +99,18 @@ public class ElasticsearchTemplateTests {
indexQuery.setObject(sampleEntity); indexQuery.setObject(sampleEntity);
elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.index(indexQuery);
//when // when
GetQuery getQuery = new GetQuery(); GetQuery getQuery = new GetQuery();
getQuery.setId(documentId); getQuery.setId(documentId);
SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class); SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(getQuery, SampleEntity.class);
//then // then
assertNotNull("not null....", sampleEntity1); assertNotNull("not null....", sampleEntity1);
assertEquals(sampleEntity, sampleEntity1); assertEquals(sampleEntity, sampleEntity1);
} }
@Test @Test
public void shouldReturnPageForGivenSearchQuery(){ public void shouldReturnPageForGivenSearchQuery() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -125,18 +125,18 @@ public class ElasticsearchTemplateTests {
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
//when // when
Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class); Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class);
//then // then
assertThat(sampleEntities, is(notNullValue())); assertThat(sampleEntities, is(notNullValue()));
assertThat(sampleEntities.getTotalElements(), greaterThanOrEqualTo(1L)); assertThat(sampleEntities.getTotalElements(), greaterThanOrEqualTo(1L));
} }
@Test @Test
public void shouldDoBulkIndex(){ public void shouldDoBulkIndex() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -148,7 +148,7 @@ public class ElasticsearchTemplateTests {
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
indexQueries.add(indexQuery1); indexQueries.add(indexQuery1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -160,18 +160,18 @@ public class ElasticsearchTemplateTests {
indexQuery2.setObject(sampleEntity2); indexQuery2.setObject(sampleEntity2);
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
//when // when
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
//then // then
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build(); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery,SampleEntity.class); Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class);
assertThat(sampleEntities.getTotalElements(), is(equalTo(2L))); assertThat(sampleEntities.getTotalElements(), is(equalTo(2L)));
} }
@Test @Test
public void shouldDeleteDocumentForGivenId(){ public void shouldDeleteDocumentForGivenId() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -183,18 +183,18 @@ public class ElasticsearchTemplateTests {
indexQuery.setObject(sampleEntity); indexQuery.setObject(sampleEntity);
elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.index(indexQuery);
//when // when
elasticsearchTemplate.delete("test-index","test-type",documentId); elasticsearchTemplate.delete("test-index", "test-type", documentId);
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
//then // then
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fieldQuery("id", documentId)).build(); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fieldQuery("id", documentId)).build();
Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery,SampleEntity.class); Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class);
assertThat(sampleEntities.getTotalElements(), equalTo(0L)); assertThat(sampleEntities.getTotalElements(), equalTo(0L));
} }
@Test @Test
public void shouldDeleteEntityForGivenId(){ public void shouldDeleteEntityForGivenId() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -206,18 +206,18 @@ public class ElasticsearchTemplateTests {
indexQuery.setObject(sampleEntity); indexQuery.setObject(sampleEntity);
elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.index(indexQuery);
//when // when
elasticsearchTemplate.delete(SampleEntity.class,documentId); elasticsearchTemplate.delete(SampleEntity.class, documentId);
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
//then // then
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fieldQuery("id", documentId)).build(); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fieldQuery("id", documentId)).build();
Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery,SampleEntity.class); Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class);
assertThat(sampleEntities.getTotalElements(), equalTo(0L)); assertThat(sampleEntities.getTotalElements(), equalTo(0L));
} }
@Test @Test
public void shouldDeleteDocumentForGivenQuery(){ public void shouldDeleteDocumentForGivenQuery() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -229,19 +229,19 @@ public class ElasticsearchTemplateTests {
indexQuery.setObject(sampleEntity); indexQuery.setObject(sampleEntity);
elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.index(indexQuery);
//when // when
DeleteQuery deleteQuery = new DeleteQuery(); DeleteQuery deleteQuery = new DeleteQuery();
deleteQuery.setQuery(fieldQuery("id", documentId)); deleteQuery.setQuery(fieldQuery("id", documentId));
elasticsearchTemplate.delete(deleteQuery,SampleEntity.class); elasticsearchTemplate.delete(deleteQuery, SampleEntity.class);
//then // then
SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fieldQuery("id",documentId)).build(); SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fieldQuery("id", documentId)).build();
Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery,SampleEntity.class); Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class);
assertThat(sampleEntities.getTotalElements(), equalTo(0L)); assertThat(sampleEntities.getTotalElements(), equalTo(0L));
} }
@Test @Test
public void shouldFilterSearchResultsForGivenFilter(){ public void shouldFilterSearchResultsForGivenFilter() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -254,21 +254,19 @@ public class ElasticsearchTemplateTests {
elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
SearchQuery searchQuery = new NativeSearchQueryBuilder() SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withQuery(matchAllQuery()) .withFilter(boolFilter().must(termFilter("id", documentId))).build();
.withFilter(boolFilter().must(termFilter("id", documentId))) // when
.build(); Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class);
//when // then
Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery,SampleEntity.class);
//then
assertThat(sampleEntities.getTotalElements(), equalTo(1L)); assertThat(sampleEntities.getTotalElements(), equalTo(1L));
} }
@Test @Test
public void shouldSortResultsGivenSortCriteria(){ public void shouldSortResultsGivenSortCriteria() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -280,7 +278,7 @@ public class ElasticsearchTemplateTests {
indexQuery1.setId(documentId); indexQuery1.setId(documentId);
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -292,7 +290,7 @@ public class ElasticsearchTemplateTests {
indexQuery2.setId(documentId2); indexQuery2.setId(documentId2);
indexQuery2.setObject(sampleEntity2); indexQuery2.setObject(sampleEntity2);
//third document // third document
String documentId3 = randomNumeric(5); String documentId3 = randomNumeric(5);
SampleEntity sampleEntity3 = new SampleEntity(); SampleEntity sampleEntity3 = new SampleEntity();
sampleEntity3.setId(documentId3); sampleEntity3.setId(documentId3);
@ -311,20 +309,18 @@ public class ElasticsearchTemplateTests {
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
SearchQuery searchQuery = new NativeSearchQueryBuilder() SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery())
.withQuery(matchAllQuery()) .withSort(new FieldSortBuilder("rate").ignoreUnmapped(true).order(SortOrder.ASC)).build();
.withSort(new FieldSortBuilder("rate").ignoreUnmapped(true).order(SortOrder.ASC)) // when
.build(); Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery, SampleEntity.class);
//when // then
Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(searchQuery,SampleEntity.class);
//then
assertThat(sampleEntities.getTotalElements(), equalTo(3L)); assertThat(sampleEntities.getTotalElements(), equalTo(3L));
assertThat(sampleEntities.getContent().get(0).getRate(),is(sampleEntity2.getRate())); assertThat(sampleEntities.getContent().get(0).getRate(), is(sampleEntity2.getRate()));
} }
@Test @Test
public void shouldExecuteStringQuery(){ public void shouldExecuteStringQuery() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -339,15 +335,15 @@ public class ElasticsearchTemplateTests {
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
StringQuery stringQuery = new StringQuery(matchAllQuery().toString()); StringQuery stringQuery = new StringQuery(matchAllQuery().toString());
//when // when
Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(stringQuery,SampleEntity.class); Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(stringQuery, SampleEntity.class);
//then // then
assertThat(sampleEntities.getTotalElements(), equalTo(1L)); assertThat(sampleEntities.getTotalElements(), equalTo(1L));
} }
@Test @Test
public void shouldReturnPageableResultsGivenStringQuery(){ public void shouldReturnPageableResultsGivenStringQuery() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -361,19 +357,19 @@ public class ElasticsearchTemplateTests {
elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
StringQuery stringQuery = new StringQuery(matchAllQuery().toString(),new PageRequest(0,10)); StringQuery stringQuery = new StringQuery(matchAllQuery().toString(), new PageRequest(0, 10));
//when // when
Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(stringQuery,SampleEntity.class); Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(stringQuery, SampleEntity.class);
//then // then
assertThat(sampleEntities.getTotalElements(), is(greaterThanOrEqualTo(1L))); assertThat(sampleEntities.getTotalElements(), is(greaterThanOrEqualTo(1L)));
} }
@Test @Test
@Ignore("By default, the search request will fail if there is no mapping associated with a field. The ignore_unmapped option allows to ignore fields that have no mapping and not sort by them") @Ignore("By default, the search request will fail if there is no mapping associated with a field. The ignore_unmapped option allows to ignore fields that have no mapping and not sort by them")
public void shouldReturnSortedPageableResultsGivenStringQuery(){ public void shouldReturnSortedPageableResultsGivenStringQuery() {
//todo // todo
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -387,16 +383,17 @@ public class ElasticsearchTemplateTests {
elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
StringQuery stringQuery = new StringQuery(matchAllQuery().toString(),new PageRequest(0,10), new Sort(new Sort.Order(Sort.Direction.ASC,"messsage"))); StringQuery stringQuery = new StringQuery(matchAllQuery().toString(), new PageRequest(0, 10), new Sort(
//when new Sort.Order(Sort.Direction.ASC, "messsage")));
Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(stringQuery,SampleEntity.class); // when
//then Page<SampleEntity> sampleEntities = elasticsearchTemplate.queryForPage(stringQuery, SampleEntity.class);
// then
assertThat(sampleEntities.getTotalElements(), is(greaterThanOrEqualTo(1L))); assertThat(sampleEntities.getTotalElements(), is(greaterThanOrEqualTo(1L)));
} }
@Test @Test
public void shouldReturnObjectMatchingGivenStringQuery(){ public void shouldReturnObjectMatchingGivenStringQuery() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -410,26 +407,25 @@ public class ElasticsearchTemplateTests {
elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
StringQuery stringQuery = new StringQuery(fieldQuery("id",documentId).toString()); StringQuery stringQuery = new StringQuery(fieldQuery("id", documentId).toString());
//when // when
SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(stringQuery, SampleEntity.class); SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(stringQuery, SampleEntity.class);
//then // then
assertThat(sampleEntity1, is(notNullValue())); assertThat(sampleEntity1, is(notNullValue()));
assertThat(sampleEntity1.getId(), is(equalTo(documentId))); assertThat(sampleEntity1.getId(), is(equalTo(documentId)));
} }
@Test @Test
public void shouldCreateIndexGivenEntityClass(){ public void shouldCreateIndexGivenEntityClass() {
//when // when
boolean created = elasticsearchTemplate.createIndex(SampleEntity.class); boolean created = elasticsearchTemplate.createIndex(SampleEntity.class);
//then // then
assertThat(created, is(true)); assertThat(created, is(true));
} }
@Test @Test
public void shouldExecuteGivenCriteriaQuery(){ public void shouldExecuteGivenCriteriaQuery() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -444,15 +440,15 @@ public class ElasticsearchTemplateTests {
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("test")); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("test"));
//when // when
SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(criteriaQuery,SampleEntity.class); SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class);
//then // then
assertThat(sampleEntity1, is(notNullValue())); assertThat(sampleEntity1, is(notNullValue()));
} }
@Test @Test
public void shouldReturnSpecifiedFields(){ public void shouldReturnSpecifiedFields() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
String message = "some test message"; String message = "some test message";
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
@ -466,37 +462,33 @@ public class ElasticsearchTemplateTests {
elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
SearchQuery searchQuery = new NativeSearchQueryBuilder() SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withIndices("test-index")
.withQuery(matchAllQuery()) .withTypes("test-type").withFields("message").build();
.withIndices("test-index") // when
.withTypes("test-type")
.withFields("message")
.build();
//when
Page<String> page = elasticsearchTemplate.queryForPage(searchQuery, new ResultsMapper<String>() { Page<String> page = elasticsearchTemplate.queryForPage(searchQuery, new ResultsMapper<String>() {
@Override @Override
public Page<String> mapResults(SearchResponse response) { public Page<String> mapResults(SearchResponse response) {
List<String> values = new ArrayList<String>(); List<String> values = new ArrayList<String>();
for(SearchHit searchHit : response.getHits()){ for (SearchHit searchHit : response.getHits()) {
values.add((String) searchHit.field("message").value()); values.add((String) searchHit.field("message").value());
} }
return new PageImpl<String>(values); return new PageImpl<String>(values);
} }
}); });
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L))); assertThat(page.getTotalElements(), is(equalTo(1L)));
assertThat(page.getContent().get(0), is(message)); assertThat(page.getContent().get(0), is(message));
} }
@Test @Test
public void shouldReturnSimilarResultsGivenMoreLikeThisQuery(){ public void shouldReturnSimilarResultsGivenMoreLikeThisQuery() {
//given // given
String sampleMessage = "So we build a web site or an application and want to add search to it, " + 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," + + "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 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 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."; + "we want real-time search, we want simple multi-tenancy, and we want a solution that is built for the cloud.";
String documentId1 = randomNumeric(5); String documentId1 = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
@ -523,24 +515,23 @@ public class ElasticsearchTemplateTests {
elasticsearchTemplate.index(indexQuery2); elasticsearchTemplate.index(indexQuery2);
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
MoreLikeThisQuery moreLikeThisQuery = new MoreLikeThisQuery(); MoreLikeThisQuery moreLikeThisQuery = new MoreLikeThisQuery();
moreLikeThisQuery.setId(documentId2); moreLikeThisQuery.setId(documentId2);
moreLikeThisQuery.addFields("message"); moreLikeThisQuery.addFields("message");
moreLikeThisQuery.setMinDocFreq(1); moreLikeThisQuery.setMinDocFreq(1);
//when // when
Page<SampleEntity> sampleEntities = elasticsearchTemplate.moreLikeThis(moreLikeThisQuery, SampleEntity.class); Page<SampleEntity> sampleEntities = elasticsearchTemplate.moreLikeThis(moreLikeThisQuery, SampleEntity.class);
//then // then
assertThat(sampleEntities.getTotalElements(), is(equalTo(1L))); assertThat(sampleEntities.getTotalElements(), is(equalTo(1L)));
assertThat(sampleEntities.getContent(), hasItem(sampleEntity1)); assertThat(sampleEntities.getContent(), hasItem(sampleEntity1));
} }
@Test @Test
public void shouldReturnResultsWithScanAndScroll(){ public void shouldReturnResultsWithScanAndScroll() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -552,7 +543,7 @@ public class ElasticsearchTemplateTests {
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
indexQueries.add(indexQuery1); indexQueries.add(indexQuery1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -564,44 +555,39 @@ public class ElasticsearchTemplateTests {
indexQuery2.setObject(sampleEntity2); indexQuery2.setObject(sampleEntity2);
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
//when // when
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
//then // then
SearchQuery searchQuery = new NativeSearchQueryBuilder() SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).withIndices("test-index")
.withQuery(matchAllQuery()) .withTypes("test-type").withPageable(new PageRequest(0, 1)).build();
.withIndices("test-index")
.withTypes("test-type")
.withPageable(new PageRequest(0,1))
.build();
String scrollId = elasticsearchTemplate.scan(searchQuery,1000,false); String scrollId = elasticsearchTemplate.scan(searchQuery, 1000, false);
List<SampleEntity> sampleEntities = new ArrayList<SampleEntity>(); List<SampleEntity> sampleEntities = new ArrayList<SampleEntity>();
boolean hasRecords = true; boolean hasRecords = true;
while (hasRecords){ while (hasRecords) {
Page<SampleEntity> page = elasticsearchTemplate.scroll(scrollId, 5000L , new ResultsMapper<SampleEntity>() { Page<SampleEntity> page = elasticsearchTemplate.scroll(scrollId, 5000L, new ResultsMapper<SampleEntity>() {
@Override @Override
public Page<SampleEntity> mapResults(SearchResponse response) { public Page<SampleEntity> mapResults(SearchResponse response) {
List<SampleEntity> chunk = new ArrayList<SampleEntity>(); List<SampleEntity> chunk = new ArrayList<SampleEntity>();
for(SearchHit searchHit : response.getHits()){ for (SearchHit searchHit : response.getHits()) {
if(response.getHits().getHits().length <= 0) { if (response.getHits().getHits().length <= 0) {
return null; return null;
} }
SampleEntity user = new SampleEntity(); SampleEntity user = new SampleEntity();
user.setId(searchHit.getId()); user.setId(searchHit.getId());
user.setMessage((String)searchHit.getSource().get("message")); user.setMessage((String) searchHit.getSource().get("message"));
chunk.add(user); chunk.add(user);
} }
return new PageImpl<SampleEntity>(chunk); return new PageImpl<SampleEntity>(chunk);
} }
}); });
if(page != null) { if (page != null) {
sampleEntities.addAll(page.getContent()); sampleEntities.addAll(page.getContent());
hasRecords = page.hasNextPage(); hasRecords = page.hasNextPage();
} } else {
else{
hasRecords = false; hasRecords = false;
} }
@ -610,10 +596,10 @@ public class ElasticsearchTemplateTests {
} }
@Test @Test
public void shouldReturnListForGivenCriteria(){ public void shouldReturnListForGivenCriteria() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -625,7 +611,7 @@ public class ElasticsearchTemplateTests {
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
indexQueries.add(indexQuery1); indexQueries.add(indexQuery1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -638,7 +624,7 @@ public class ElasticsearchTemplateTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
//second document // second document
String documentId3 = randomNumeric(5); String documentId3 = randomNumeric(5);
SampleEntity sampleEntity3 = new SampleEntity(); SampleEntity sampleEntity3 = new SampleEntity();
sampleEntity3.setId(documentId3); sampleEntity3.setId(documentId3);
@ -650,24 +636,27 @@ public class ElasticsearchTemplateTests {
indexQuery3.setObject(sampleEntity3); indexQuery3.setObject(sampleEntity3);
indexQueries.add(indexQuery3); indexQueries.add(indexQuery3);
//when // when
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
//when // when
CriteriaQuery singleCriteriaQuery = new CriteriaQuery(new Criteria("message").contains("test")); CriteriaQuery singleCriteriaQuery = new CriteriaQuery(new Criteria("message").contains("test"));
CriteriaQuery multipleCriteriaQuery = new CriteriaQuery(new Criteria("message").contains("some").and("message").contains("message")); CriteriaQuery multipleCriteriaQuery = new CriteriaQuery(new Criteria("message").contains("some").and("message")
List<SampleEntity> sampleEntitiesForSingleCriteria = elasticsearchTemplate.queryForList(singleCriteriaQuery,SampleEntity.class); .contains("message"));
List<SampleEntity> sampleEntitiesForAndCriteria = elasticsearchTemplate.queryForList(multipleCriteriaQuery,SampleEntity.class); List<SampleEntity> sampleEntitiesForSingleCriteria = elasticsearchTemplate.queryForList(singleCriteriaQuery,
//then SampleEntity.class);
assertThat(sampleEntitiesForSingleCriteria.size(),is(2)); List<SampleEntity> sampleEntitiesForAndCriteria = elasticsearchTemplate.queryForList(multipleCriteriaQuery,
assertThat(sampleEntitiesForAndCriteria.size(),is(1)); SampleEntity.class);
// then
assertThat(sampleEntitiesForSingleCriteria.size(), is(2));
assertThat(sampleEntitiesForAndCriteria.size(), is(1));
} }
@Test @Test
public void shouldReturnListForGivenStringQuery(){ public void shouldReturnListForGivenStringQuery() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -679,7 +668,7 @@ public class ElasticsearchTemplateTests {
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
indexQueries.add(indexQuery1); indexQueries.add(indexQuery1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -692,7 +681,7 @@ public class ElasticsearchTemplateTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
//second document // second document
String documentId3 = randomNumeric(5); String documentId3 = randomNumeric(5);
SampleEntity sampleEntity3 = new SampleEntity(); SampleEntity sampleEntity3 = new SampleEntity();
sampleEntity3.setId(documentId3); sampleEntity3.setId(documentId3);
@ -704,35 +693,33 @@ public class ElasticsearchTemplateTests {
indexQuery3.setObject(sampleEntity3); indexQuery3.setObject(sampleEntity3);
indexQueries.add(indexQuery3); indexQueries.add(indexQuery3);
//when // when
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
//when // when
StringQuery stringQuery = new StringQuery(matchAllQuery().toString()); StringQuery stringQuery = new StringQuery(matchAllQuery().toString());
List<SampleEntity> sampleEntities = elasticsearchTemplate.queryForList(stringQuery,SampleEntity.class); List<SampleEntity> sampleEntities = elasticsearchTemplate.queryForList(stringQuery, SampleEntity.class);
//then // then
assertThat(sampleEntities.size(),is(3)); assertThat(sampleEntities.size(), is(3));
} }
@Test @Test
public void shouldPutMappingForGivenEntity()throws Exception{ public void shouldPutMappingForGivenEntity() throws Exception {
//given // given
Class entity = SampleMappingEntity.class; Class entity = SampleMappingEntity.class;
elasticsearchTemplate.createIndex(entity); elasticsearchTemplate.createIndex(entity);
//when // when
assertThat(elasticsearchTemplate.putMapping(entity) , is(true)) ; assertThat(elasticsearchTemplate.putMapping(entity), is(true));
} }
@Test @Test
public void shouldDeleteIndexForGivenEntity(){ public void shouldDeleteIndexForGivenEntity() {
//given // given
Class clazz = SampleEntity.class; Class clazz = SampleEntity.class;
//when // when
elasticsearchTemplate.deleteIndex(clazz); elasticsearchTemplate.deleteIndex(clazz);
//then // then
assertThat(elasticsearchTemplate.indexExists(clazz),is(false)); assertThat(elasticsearchTemplate.indexExists(clazz), is(false));
} }
} }

View File

@ -38,9 +38,9 @@ public class DateTimeConvertersTests {
@Test @Test
public void testJodaDateTimeConverter() { public void testJodaDateTimeConverter() {
DateTime dateTime = new DateTime(2013, 1,24 , 6, 35, 0, DateTimeZone.UTC); DateTime dateTime = new DateTime(2013, 1, 24, 6, 35, 0, DateTimeZone.UTC);
Assert.assertEquals("2013-01-24T06:35:00.000Z", Assert
DateTimeConverters.JodaDateTimeConverter.INSTANCE.convert(dateTime)); .assertEquals("2013-01-24T06:35:00.000Z", DateTimeConverters.JodaDateTimeConverter.INSTANCE.convert(dateTime));
} }
@Test @Test
@ -50,7 +50,7 @@ public class DateTimeConvertersTests {
@Test @Test
public void testJodaLocalDateTimeConverter() { public void testJodaLocalDateTimeConverter() {
LocalDateTime dateTime = new LocalDateTime(new DateTime(2013, 1,24, 6, 35, 0, DateTimeZone.UTC).getMillis(), LocalDateTime dateTime = new LocalDateTime(new DateTime(2013, 1, 24, 6, 35, 0, DateTimeZone.UTC).getMillis(),
DateTimeZone.UTC); DateTimeZone.UTC);
Assert.assertEquals("2013-01-24T06:35:00.000Z", Assert.assertEquals("2013-01-24T06:35:00.000Z",
DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE.convert(dateTime)); DateTimeConverters.JodaLocalDateTimeConverter.INSTANCE.convert(dateTime));
@ -63,7 +63,7 @@ public class DateTimeConvertersTests {
@Test @Test
public void testJavaDateConverter() { public void testJavaDateConverter() {
DateTime dateTime = new DateTime(2013, 1,24, 6, 35, 0, DateTimeZone.UTC); DateTime dateTime = new DateTime(2013, 1, 24, 6, 35, 0, DateTimeZone.UTC);
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
calendar.setTimeZone(TimeZone.getTimeZone("UTC")); calendar.setTimeZone(TimeZone.getTimeZone("UTC"));
calendar.setTimeInMillis(dateTime.getMillis()); calendar.setTimeInMillis(dateTime.getMillis());

View File

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

View File

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

View File

@ -32,6 +32,7 @@ import static org.apache.commons.lang.RandomStringUtils.randomNumeric;
import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*; import static org.junit.Assert.*;
/** /**
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
@ -44,17 +45,17 @@ public class CriteriaQueryTests {
private ElasticsearchTemplate elasticsearchTemplate; private ElasticsearchTemplate elasticsearchTemplate;
@Before @Before
public void before(){ public void before() {
elasticsearchTemplate.createIndex(SampleEntity.class); elasticsearchTemplate.createIndex(SampleEntity.class);
DeleteQuery deleteQuery = new DeleteQuery(); DeleteQuery deleteQuery = new DeleteQuery();
deleteQuery.setQuery(matchAllQuery()); deleteQuery.setQuery(matchAllQuery());
elasticsearchTemplate.delete(deleteQuery,SampleEntity.class); elasticsearchTemplate.delete(deleteQuery, SampleEntity.class);
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
} }
@Test @Test
public void shouldPerformAndOperation(){ public void shouldPerformAndOperation() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -66,18 +67,19 @@ public class CriteriaQueryTests {
indexQuery.setObject(sampleEntity); indexQuery.setObject(sampleEntity);
elasticsearchTemplate.index(indexQuery); elasticsearchTemplate.index(indexQuery);
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("test").and("message").contains("some")); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("test").and("message")
//when .contains("some"));
SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(criteriaQuery,SampleEntity.class); // when
//then SampleEntity sampleEntity1 = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class);
// then
assertThat(sampleEntity1, is(notNullValue())); assertThat(sampleEntity1, is(notNullValue()));
} }
@Test @Test
public void shouldPerformOrOperation(){ public void shouldPerformOrOperation() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -89,7 +91,7 @@ public class CriteriaQueryTests {
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
indexQueries.add(indexQuery1); indexQueries.add(indexQuery1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -102,20 +104,21 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("some").or("message").contains("test")); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("some").or("message")
//when .contains("test"));
// when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(),is(greaterThanOrEqualTo(1L))); assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
} }
@Test @Test
public void shouldPerformAndOperationWithinCriteria(){ public void shouldPerformAndOperationWithinCriteria() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -128,21 +131,20 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery); indexQueries.add(indexQuery);
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria().and(new Criteria("message").contains("some"))); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria().and(new Criteria("message").contains("some")));
//when // when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(),is(greaterThanOrEqualTo(1L))); assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
} }
@Test @Test
public void shouldPerformOrOperationWithinCriteria(){ public void shouldPerformOrOperationWithinCriteria() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -155,20 +157,20 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery); indexQueries.add(indexQuery);
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria().or(new Criteria("message").contains("some"))); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria().or(new Criteria("message").contains("some")));
//when // when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(),is(greaterThanOrEqualTo(1L))); assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
} }
@Test @Test
public void shouldPerformIsOperation() { public void shouldPerformIsOperation() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -181,20 +183,20 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery); indexQueries.add(indexQuery);
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message")); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message"));
//when // when
Page<SampleEntity> page= elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
//then // then
assertThat("message", is(criteriaQuery.getCriteria().getField().getName())); assertThat("message", is(criteriaQuery.getCriteria().getField().getName()));
assertThat(page.getTotalElements(),is(greaterThanOrEqualTo(1L))); assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
} }
@Test @Test
public void shouldPerformMultipleIsOperations() { public void shouldPerformMultipleIsOperations() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -206,7 +208,7 @@ public class CriteriaQueryTests {
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
indexQueries.add(indexQuery1); indexQueries.add(indexQuery1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -219,20 +221,20 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message").is("test message")); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("some message").is("test message"));
//when // when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery,SampleEntity.class); Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
//then // then
assertThat("message", is(criteriaQuery.getCriteria().getField().getName())); assertThat("message", is(criteriaQuery.getCriteria().getField().getName()));
assertThat(page.getTotalElements(),is(greaterThanOrEqualTo(2L))); assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(2L)));
} }
@Test @Test
public void shouldPerformEndsWithOperation() { public void shouldPerformEndsWithOperation() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -244,7 +246,7 @@ public class CriteriaQueryTests {
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
indexQueries.add(indexQuery1); indexQueries.add(indexQuery1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -257,21 +259,21 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
Criteria criteria = new Criteria("message").endsWith("end"); Criteria criteria = new Criteria("message").endsWith("end");
CriteriaQuery criteriaQuery = new CriteriaQuery(criteria); CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
//when // when
SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class); SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class);
//then // then
assertThat("message", is(criteriaQuery.getCriteria().getField().getName())); assertThat("message", is(criteriaQuery.getCriteria().getField().getName()));
assertThat(sampleEntity, is(notNullValue())); assertThat(sampleEntity, is(notNullValue()));
} }
@Test @Test
public void shouldPerformStartsWithOperation() { public void shouldPerformStartsWithOperation() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -283,7 +285,7 @@ public class CriteriaQueryTests {
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
indexQueries.add(indexQuery1); indexQueries.add(indexQuery1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -296,21 +298,21 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
Criteria criteria = new Criteria("message").startsWith("start"); Criteria criteria = new Criteria("message").startsWith("start");
CriteriaQuery criteriaQuery = new CriteriaQuery(criteria); CriteriaQuery criteriaQuery = new CriteriaQuery(criteria);
//when // when
SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery,SampleEntity.class); SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class);
//then // then
assertThat("message", is(criteriaQuery.getCriteria().getField().getName())); assertThat("message", is(criteriaQuery.getCriteria().getField().getName()));
assertThat(sampleEntity,is(notNullValue())); assertThat(sampleEntity, is(notNullValue()));
} }
@Test @Test
public void shouldPerformContainsOperation() { public void shouldPerformContainsOperation() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -322,7 +324,7 @@ public class CriteriaQueryTests {
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
indexQueries.add(indexQuery1); indexQueries.add(indexQuery1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -335,21 +337,21 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
CriteriaQuery criteriaQuery= new CriteriaQuery(new Criteria("message").contains("contains")); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("contains"));
//when // when
SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery,SampleEntity.class); SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class);
//then // then
assertThat("message", is(criteriaQuery.getCriteria().getField().getName())); assertThat("message", is(criteriaQuery.getCriteria().getField().getName()));
assertThat(sampleEntity,is(notNullValue())); assertThat(sampleEntity, is(notNullValue()));
} }
@Test @Test
public void shouldExecuteExpression() { public void shouldExecuteExpression() {
//given // given
//todo // todo
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -361,7 +363,7 @@ public class CriteriaQueryTests {
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
indexQueries.add(indexQuery1); indexQueries.add(indexQuery1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -374,20 +376,20 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
CriteriaQuery criteriaQuery= new CriteriaQuery(new Criteria("message").expression("+elasticsearch || test")); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").expression("+elasticsearch || test"));
//when // when
SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class); SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class);
//then // then
assertThat("message", is(criteriaQuery.getCriteria().getField().getName())); assertThat("message", is(criteriaQuery.getCriteria().getField().getName()));
assertThat(sampleEntity,is(notNullValue())); assertThat(sampleEntity, is(notNullValue()));
} }
@Test @Test
public void shouldExecuteCriteriaChain() { public void shouldExecuteCriteriaChain() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -399,7 +401,7 @@ public class CriteriaQueryTests {
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
indexQueries.add(indexQuery1); indexQueries.add(indexQuery1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -412,20 +414,21 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").startsWith("some").endsWith("search").contains("message").is("some message search")); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").startsWith("some").endsWith("search")
//when .contains("message").is("some message search"));
SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery,SampleEntity.class); // when
//then SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class);
// then
assertThat("message", is(criteriaQuery.getCriteria().getField().getName())); assertThat("message", is(criteriaQuery.getCriteria().getField().getName()));
assertThat(sampleEntity, is(notNullValue())); assertThat(sampleEntity, is(notNullValue()));
} }
@Test @Test
public void shouldPerformIsNotOperation() { public void shouldPerformIsNotOperation() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -437,7 +440,7 @@ public class CriteriaQueryTests {
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
indexQueries.add(indexQuery1); indexQueries.add(indexQuery1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -450,21 +453,21 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("foo").not()); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").is("foo").not());
//when // when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
//then // then
assertTrue(criteriaQuery.getCriteria().isNegating()); assertTrue(criteriaQuery.getCriteria().isNegating());
assertThat(page,is(notNullValue())); assertThat(page, is(notNullValue()));
assertFalse(page.iterator().next().getMessage().contains("foo")); assertFalse(page.iterator().next().getMessage().contains("foo"));
} }
@Test @Test
public void shouldPerformBetweenOperation() { public void shouldPerformBetweenOperation() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -477,7 +480,7 @@ public class CriteriaQueryTests {
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
indexQueries.add(indexQuery1); indexQueries.add(indexQuery1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -491,19 +494,19 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(100,150)); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(100, 150));
//when // when
SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class); SampleEntity sampleEntity = elasticsearchTemplate.queryForObject(criteriaQuery, SampleEntity.class);
//then // then
assertThat(sampleEntity,is(notNullValue())); assertThat(sampleEntity, is(notNullValue()));
} }
@Test @Test
public void shouldPerformBetweenOperationWithoutUpperBound() { public void shouldPerformBetweenOperationWithoutUpperBound() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -516,7 +519,7 @@ public class CriteriaQueryTests {
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
indexQueries.add(indexQuery1); indexQueries.add(indexQuery1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -530,20 +533,20 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(350,null)); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(350, null));
//when // when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
//then // then
assertThat(page,is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(),is(greaterThanOrEqualTo(1L))); assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
} }
@Test @Test
public void shouldPerformBetweenOperationWithoutLowerBound() { public void shouldPerformBetweenOperationWithoutLowerBound() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -556,7 +559,7 @@ public class CriteriaQueryTests {
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
indexQueries.add(indexQuery1); indexQueries.add(indexQuery1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -570,20 +573,20 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(null,550)); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").between(null, 550));
//when // when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
//then // then
assertThat(page,is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(),is(greaterThanOrEqualTo(1L))); assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
} }
@Test @Test
public void shouldPerformLessThanEqualOperation() { public void shouldPerformLessThanEqualOperation() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -596,7 +599,7 @@ public class CriteriaQueryTests {
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
indexQueries.add(indexQuery1); indexQueries.add(indexQuery1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -610,20 +613,20 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").lessThanEqual(750)); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").lessThanEqual(750));
//when // when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
//then // then
assertThat(page,is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(),is(greaterThanOrEqualTo(1L))); assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
} }
@Test @Test
public void shouldPerformGreaterThanEquals() { public void shouldPerformGreaterThanEquals() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -636,7 +639,7 @@ public class CriteriaQueryTests {
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
indexQueries.add(indexQuery1); indexQueries.add(indexQuery1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -650,20 +653,20 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").greaterThanEqual(950)); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("rate").greaterThanEqual(950));
//when // when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
//then // then
assertThat(page,is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(),is(greaterThanOrEqualTo(1L))); assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
} }
@Test @Test
public void shouldPerformBoostOperation() { public void shouldPerformBoostOperation() {
//given // given
List<IndexQuery> indexQueries = new ArrayList<IndexQuery>(); List<IndexQuery> indexQueries = new ArrayList<IndexQuery>();
//first document // first document
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -676,7 +679,7 @@ public class CriteriaQueryTests {
indexQuery1.setObject(sampleEntity1); indexQuery1.setObject(sampleEntity1);
indexQueries.add(indexQuery1); indexQueries.add(indexQuery1);
//second document // second document
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -690,11 +693,11 @@ public class CriteriaQueryTests {
indexQueries.add(indexQuery2); indexQueries.add(indexQuery2);
elasticsearchTemplate.bulkIndex(indexQueries); elasticsearchTemplate.bulkIndex(indexQueries);
elasticsearchTemplate.refresh(SampleEntity.class,true); elasticsearchTemplate.refresh(SampleEntity.class, true);
CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("foo").boost(1)); CriteriaQuery criteriaQuery = new CriteriaQuery(new Criteria("message").contains("foo").boost(1));
//when // when
Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class); Page<SampleEntity> page = elasticsearchTemplate.queryForPage(criteriaQuery, SampleEntity.class);
//then // then
assertThat(page.getTotalElements(),is(greaterThanOrEqualTo(1L))); assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
} }
} }

View File

@ -15,7 +15,6 @@
*/ */
package org.springframework.data.elasticsearch.repositories; package org.springframework.data.elasticsearch.repositories;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; 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.elasticsearch.index.query.QueryBuilders.matchAllQuery;
import static org.hamcrest.Matchers.*; import static org.hamcrest.Matchers.*;
import static org.junit.Assert.assertThat; import static org.junit.Assert.assertThat;
/** /**
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
@ -53,66 +53,65 @@ public class CustomMethodRepositoryTests {
private ElasticsearchTemplate elasticsearchTemplate; private ElasticsearchTemplate elasticsearchTemplate;
@Before @Before
public void before(){ public void before() {
elasticsearchTemplate.createIndex(SampleEntity.class); elasticsearchTemplate.createIndex(SampleEntity.class);
DeleteQuery deleteQuery = new DeleteQuery(); DeleteQuery deleteQuery = new DeleteQuery();
deleteQuery.setQuery(matchAllQuery()); deleteQuery.setQuery(matchAllQuery());
elasticsearchTemplate.delete(deleteQuery,SampleEntity.class); elasticsearchTemplate.delete(deleteQuery, SampleEntity.class);
elasticsearchTemplate.refresh(SampleEntity.class, true); elasticsearchTemplate.refresh(SampleEntity.class, true);
} }
@Test @Test
public void shouldExecuteCustomMethod(){ public void shouldExecuteCustomMethod() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
sampleEntity.setType("test"); sampleEntity.setType("test");
sampleEntity.setMessage("some message"); sampleEntity.setMessage("some message");
repository.save(sampleEntity); repository.save(sampleEntity);
//when // when
Page<SampleEntity> page = repository.findByType("test", new PageRequest(0, 10)); Page<SampleEntity> page = repository.findByType("test", new PageRequest(0, 10));
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
} }
@Test @Test
public void shouldExecuteCustomMethodForNot(){ public void shouldExecuteCustomMethodForNot() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
sampleEntity.setType("some"); sampleEntity.setType("some");
sampleEntity.setMessage("some message"); sampleEntity.setMessage("some message");
repository.save(sampleEntity); repository.save(sampleEntity);
//when // when
Page<SampleEntity> page = repository.findByTypeNot("test", new PageRequest(0, 10)); Page<SampleEntity> page = repository.findByTypeNot("test", new PageRequest(0, 10));
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L))); assertThat(page.getTotalElements(), is(equalTo(1L)));
} }
@Test @Test
public void shouldExecuteCustomMethodWithQuery(){ public void shouldExecuteCustomMethodWithQuery() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
sampleEntity.setType("test"); sampleEntity.setType("test");
sampleEntity.setMessage("customQuery"); sampleEntity.setMessage("customQuery");
repository.save(sampleEntity); repository.save(sampleEntity);
//when // when
Page<SampleEntity> page = repository.findByMessage("customQuery", new PageRequest(0, 10)); Page<SampleEntity> page = repository.findByMessage("customQuery", new PageRequest(0, 10));
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L))); assertThat(page.getTotalElements(), is(greaterThanOrEqualTo(1L)));
} }
@Test @Test
public void shouldExecuteCustomMethodWithLessThan(){ public void shouldExecuteCustomMethodWithLessThan() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -129,16 +128,16 @@ public class CustomMethodRepositoryTests {
sampleEntity2.setMessage("some message"); sampleEntity2.setMessage("some message");
repository.save(sampleEntity2); repository.save(sampleEntity2);
//when // when
Page<SampleEntity> page = repository.findByRateLessThan(10, new PageRequest(0, 10)); Page<SampleEntity> page = repository.findByRateLessThan(10, new PageRequest(0, 10));
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L))); assertThat(page.getTotalElements(), is(equalTo(1L)));
} }
@Test @Test
public void shouldExecuteCustomMethodWithBefore(){ public void shouldExecuteCustomMethodWithBefore() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -147,16 +146,16 @@ public class CustomMethodRepositoryTests {
sampleEntity.setMessage("some message"); sampleEntity.setMessage("some message");
repository.save(sampleEntity); repository.save(sampleEntity);
//when // when
Page<SampleEntity> page = repository.findByRateBefore(10, new PageRequest(0, 10)); Page<SampleEntity> page = repository.findByRateBefore(10, new PageRequest(0, 10));
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L))); assertThat(page.getTotalElements(), is(equalTo(1L)));
} }
@Test @Test
public void shouldExecuteCustomMethodWithAfter(){ public void shouldExecuteCustomMethodWithAfter() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -165,16 +164,16 @@ public class CustomMethodRepositoryTests {
sampleEntity.setMessage("some message"); sampleEntity.setMessage("some message");
repository.save(sampleEntity); repository.save(sampleEntity);
//when // when
Page<SampleEntity> page = repository.findByRateAfter(10, new PageRequest(0, 10)); Page<SampleEntity> page = repository.findByRateAfter(10, new PageRequest(0, 10));
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L))); assertThat(page.getTotalElements(), is(equalTo(1L)));
} }
@Test @Test
public void shouldExecuteCustomMethodWithLike(){ public void shouldExecuteCustomMethodWithLike() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -183,16 +182,16 @@ public class CustomMethodRepositoryTests {
sampleEntity.setMessage("foo"); sampleEntity.setMessage("foo");
repository.save(sampleEntity); repository.save(sampleEntity);
//when // when
Page<SampleEntity> page = repository.findByMessageLike("fo", new PageRequest(0, 10)); Page<SampleEntity> page = repository.findByMessageLike("fo", new PageRequest(0, 10));
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L))); assertThat(page.getTotalElements(), is(equalTo(1L)));
} }
@Test @Test
public void shouldExecuteCustomMethodForStartingWith(){ public void shouldExecuteCustomMethodForStartingWith() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -201,16 +200,16 @@ public class CustomMethodRepositoryTests {
sampleEntity.setMessage("foo"); sampleEntity.setMessage("foo");
repository.save(sampleEntity); repository.save(sampleEntity);
//when // when
Page<SampleEntity> page = repository.findByMessageStartingWith("fo", new PageRequest(0, 10)); Page<SampleEntity> page = repository.findByMessageStartingWith("fo", new PageRequest(0, 10));
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L))); assertThat(page.getTotalElements(), is(equalTo(1L)));
} }
@Test @Test
public void shouldExecuteCustomMethodForEndingWith(){ public void shouldExecuteCustomMethodForEndingWith() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -219,16 +218,16 @@ public class CustomMethodRepositoryTests {
sampleEntity.setMessage("foo"); sampleEntity.setMessage("foo");
repository.save(sampleEntity); repository.save(sampleEntity);
//when // when
Page<SampleEntity> page = repository.findByMessageEndingWith("o", new PageRequest(0, 10)); Page<SampleEntity> page = repository.findByMessageEndingWith("o", new PageRequest(0, 10));
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L))); assertThat(page.getTotalElements(), is(equalTo(1L)));
} }
@Test @Test
public void shouldExecuteCustomMethodForContains(){ public void shouldExecuteCustomMethodForContains() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -237,16 +236,16 @@ public class CustomMethodRepositoryTests {
sampleEntity.setMessage("foo"); sampleEntity.setMessage("foo");
repository.save(sampleEntity); repository.save(sampleEntity);
//when // when
Page<SampleEntity> page = repository.findByMessageContaining("fo", new PageRequest(0, 10)); Page<SampleEntity> page = repository.findByMessageContaining("fo", new PageRequest(0, 10));
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L))); assertThat(page.getTotalElements(), is(equalTo(1L)));
} }
@Test @Test
public void shouldExecuteCustomMethodForIn(){ public void shouldExecuteCustomMethodForIn() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -254,7 +253,7 @@ public class CustomMethodRepositoryTests {
sampleEntity.setMessage("foo"); sampleEntity.setMessage("foo");
repository.save(sampleEntity); repository.save(sampleEntity);
//given // given
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -262,18 +261,18 @@ public class CustomMethodRepositoryTests {
sampleEntity2.setMessage("bar"); sampleEntity2.setMessage("bar");
repository.save(sampleEntity2); repository.save(sampleEntity2);
List<String> ids = Arrays.asList(documentId,documentId2); List<String> ids = Arrays.asList(documentId, documentId2);
//when // when
Page<SampleEntity> page = repository.findByIdIn(ids, new PageRequest(0, 10)); Page<SampleEntity> page = repository.findByIdIn(ids, new PageRequest(0, 10));
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(2L))); assertThat(page.getTotalElements(), is(equalTo(2L)));
} }
@Test @Test
public void shouldExecuteCustomMethodForNotIn(){ public void shouldExecuteCustomMethodForNotIn() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -281,7 +280,7 @@ public class CustomMethodRepositoryTests {
sampleEntity.setMessage("foo"); sampleEntity.setMessage("foo");
repository.save(sampleEntity); repository.save(sampleEntity);
//given // given
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -291,17 +290,17 @@ public class CustomMethodRepositoryTests {
List<String> ids = Arrays.asList(documentId); List<String> ids = Arrays.asList(documentId);
//when // when
Page<SampleEntity> page = repository.findByIdNotIn(ids, new PageRequest(0, 10)); Page<SampleEntity> page = repository.findByIdNotIn(ids, new PageRequest(0, 10));
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L))); assertThat(page.getTotalElements(), is(equalTo(1L)));
assertThat(page.getContent().get(0).getId(),is(documentId2)); assertThat(page.getContent().get(0).getId(), is(documentId2));
} }
@Test @Test
public void shouldExecuteCustomMethodForTrue(){ public void shouldExecuteCustomMethodForTrue() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -310,7 +309,7 @@ public class CustomMethodRepositoryTests {
sampleEntity.setAvailable(true); sampleEntity.setAvailable(true);
repository.save(sampleEntity); repository.save(sampleEntity);
//given // given
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -318,16 +317,16 @@ public class CustomMethodRepositoryTests {
sampleEntity2.setMessage("bar"); sampleEntity2.setMessage("bar");
sampleEntity2.setAvailable(false); sampleEntity2.setAvailable(false);
repository.save(sampleEntity2); repository.save(sampleEntity2);
//when // when
Page<SampleEntity> page = repository.findByAvailableTrue(new PageRequest(0, 10)); Page<SampleEntity> page = repository.findByAvailableTrue(new PageRequest(0, 10));
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L))); assertThat(page.getTotalElements(), is(equalTo(1L)));
} }
@Test @Test
public void shouldExecuteCustomMethodForFalse(){ public void shouldExecuteCustomMethodForFalse() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -336,7 +335,7 @@ public class CustomMethodRepositoryTests {
sampleEntity.setAvailable(true); sampleEntity.setAvailable(true);
repository.save(sampleEntity); repository.save(sampleEntity);
//given // given
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -344,16 +343,16 @@ public class CustomMethodRepositoryTests {
sampleEntity2.setMessage("bar"); sampleEntity2.setMessage("bar");
sampleEntity2.setAvailable(false); sampleEntity2.setAvailable(false);
repository.save(sampleEntity2); repository.save(sampleEntity2);
//when // when
Page<SampleEntity> page = repository.findByAvailableFalse(new PageRequest(0, 10)); Page<SampleEntity> page = repository.findByAvailableFalse(new PageRequest(0, 10));
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L))); assertThat(page.getTotalElements(), is(equalTo(1L)));
} }
@Test @Test
public void shouldExecuteCustomMethodForOrderBy(){ public void shouldExecuteCustomMethodForOrderBy() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -362,7 +361,7 @@ public class CustomMethodRepositoryTests {
sampleEntity.setAvailable(true); sampleEntity.setAvailable(true);
repository.save(sampleEntity); repository.save(sampleEntity);
//document 2 // document 2
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -371,7 +370,7 @@ public class CustomMethodRepositoryTests {
sampleEntity2.setAvailable(false); sampleEntity2.setAvailable(false);
repository.save(sampleEntity2); repository.save(sampleEntity2);
//document 3 // document 3
String documentId3 = randomNumeric(5); String documentId3 = randomNumeric(5);
SampleEntity sampleEntity3 = new SampleEntity(); SampleEntity sampleEntity3 = new SampleEntity();
sampleEntity3.setId(documentId3); sampleEntity3.setId(documentId3);
@ -380,16 +379,16 @@ public class CustomMethodRepositoryTests {
sampleEntity3.setAvailable(false); sampleEntity3.setAvailable(false);
repository.save(sampleEntity3); repository.save(sampleEntity3);
//when // when
Page<SampleEntity> page = repository.findByMessageOrderByTypeAsc("foo",new PageRequest(0, 10)); Page<SampleEntity> page = repository.findByMessageOrderByTypeAsc("foo", new PageRequest(0, 10));
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L))); assertThat(page.getTotalElements(), is(equalTo(1L)));
} }
@Test @Test
public void shouldExecuteCustomMethodWithBooleanParameter(){ public void shouldExecuteCustomMethodWithBooleanParameter() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -398,7 +397,7 @@ public class CustomMethodRepositoryTests {
sampleEntity.setAvailable(true); sampleEntity.setAvailable(true);
repository.save(sampleEntity); repository.save(sampleEntity);
//given // given
String documentId2 = randomNumeric(5); String documentId2 = randomNumeric(5);
SampleEntity sampleEntity2 = new SampleEntity(); SampleEntity sampleEntity2 = new SampleEntity();
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
@ -406,9 +405,9 @@ public class CustomMethodRepositoryTests {
sampleEntity2.setMessage("bar"); sampleEntity2.setMessage("bar");
sampleEntity2.setAvailable(false); sampleEntity2.setAvailable(false);
repository.save(sampleEntity2); repository.save(sampleEntity2);
//when // when
Page<SampleEntity> page = repository.findByAvailable(false, new PageRequest(0, 10)); Page<SampleEntity> page = repository.findByAvailable(false, new PageRequest(0, 10));
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getTotalElements(), is(equalTo(1L))); assertThat(page.getTotalElements(), is(equalTo(1L)));
} }
@ -425,15 +424,16 @@ public class CustomMethodRepositoryTests {
repository.save(sampleEntity); repository.save(sampleEntity);
} }
// when // when
Page<SampleEntity> pageResult = repository.findByMessage("message", new PageRequest(0, 23, new Sort(new Sort.Order(Sort.Direction.ASC,"message")))); Page<SampleEntity> pageResult = repository.findByMessage("message", new PageRequest(0, 23, new Sort(new Sort.Order(
Sort.Direction.ASC, "message"))));
// then // then
assertThat(pageResult.getTotalElements(), is(equalTo(30L))); assertThat(pageResult.getTotalElements(), is(equalTo(30L)));
assertThat(pageResult.getContent().size(), is(equalTo(23))); assertThat(pageResult.getContent().size(), is(equalTo(23)));
} }
@Test @Test
public void shouldReturnPageableResultsWithGivenSortingOrder(){ public void shouldReturnPageableResultsWithGivenSortingOrder() {
//given // given
String documentId = random(5); String documentId = random(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -454,17 +454,17 @@ public class CustomMethodRepositoryTests {
sampleEntity3.setMessage("abe"); sampleEntity3.setMessage("abe");
sampleEntity.setVersion(System.currentTimeMillis()); sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity3); repository.save(sampleEntity3);
//when // when
Page<SampleEntity> pageResult = repository.findByMessageContaining("a", new PageRequest(0, 23, new Sort(new Sort.Order(Sort.Direction.DESC,"message")))); Page<SampleEntity> pageResult = repository.findByMessageContaining("a", new PageRequest(0, 23, new Sort(
//then new Sort.Order(Sort.Direction.DESC, "message"))));
assertThat(pageResult.getContent().isEmpty(),is(false)); // then
assertThat(pageResult.getContent().get(0).getMessage(),is(sampleEntity3.getMessage())); assertThat(pageResult.getContent().isEmpty(), is(false));
assertThat(pageResult.getContent().get(0).getMessage(), is(sampleEntity3.getMessage()));
} }
@Test @Test
public void shouldReturnListForMessage(){ public void shouldReturnListForMessage() {
//given // given
String documentId = random(5); String documentId = random(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -485,15 +485,11 @@ public class CustomMethodRepositoryTests {
sampleEntity3.setMessage("abe"); sampleEntity3.setMessage("abe");
sampleEntity.setVersion(System.currentTimeMillis()); sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity3); repository.save(sampleEntity3);
//when // when
List<SampleEntity> sampleEntities = repository.findByMessage("abc"); List<SampleEntity> sampleEntities = repository.findByMessage("abc");
//then // then
assertThat(sampleEntities.isEmpty(),is(false)); assertThat(sampleEntities.isEmpty(), is(false));
assertThat(sampleEntities.size(),is(1)); 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.DoubleIDEntity;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; 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.IntegerIDEntity;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; 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 Rizwan Idrees
* @author Mohsin Husen * @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; package org.springframework.data.elasticsearch.repositories;
import org.springframework.data.domain.Page; import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable; import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.SampleEntity; import org.springframework.data.elasticsearch.SampleEntity;
@ -23,11 +22,12 @@ import org.springframework.data.elasticsearch.annotations.Query;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import java.util.List; import java.util.List;
/** /**
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @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);
@ -63,6 +63,6 @@ public interface SampleCustomMethodRepository extends ElasticsearchRepository<Sa
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 Rizwan Idrees
* @author Mohsin Husen * @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.SampleEntity;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
/** /**
* @author Rizwan Idrees * @author Rizwan Idrees
* @author Mohsin Husen * @author Mohsin Husen
*/ */
public interface SampleElasticsearchRepository extends ElasticsearchRepository<SampleEntity,String> { public interface SampleElasticsearchRepository extends ElasticsearchRepository<SampleEntity, String> {
} }

View File

@ -42,13 +42,13 @@ public class DoubleIDRepositoryTests {
private DoubleIDRepository repository; private DoubleIDRepository repository;
@Before @Before
public void before(){ public void before() {
repository.deleteAll(); repository.deleteAll();
} }
@Test @Test
public void shouldDoBulkIndexDocument(){ public void shouldDoBulkIndexDocument() {
//given // given
Double documentId1 = RandomUtils.nextDouble(); Double documentId1 = RandomUtils.nextDouble();
DoubleIDEntity sampleEntity1 = new DoubleIDEntity(); DoubleIDEntity sampleEntity1 = new DoubleIDEntity();
sampleEntity1.setId(documentId1); sampleEntity1.setId(documentId1);
@ -61,9 +61,9 @@ public class DoubleIDRepositoryTests {
sampleEntity2.setMessage("some message"); sampleEntity2.setMessage("some message");
sampleEntity2.setVersion(System.currentTimeMillis()); sampleEntity2.setVersion(System.currentTimeMillis());
//when // when
repository.save(Arrays.asList(sampleEntity1, sampleEntity2)); repository.save(Arrays.asList(sampleEntity1, sampleEntity2));
//then // then
DoubleIDEntity entity1FromElasticSearch = repository.findOne(documentId1); DoubleIDEntity entity1FromElasticSearch = repository.findOne(documentId1);
assertThat(entity1FromElasticSearch, is(notNullValue())); assertThat(entity1FromElasticSearch, is(notNullValue()));
@ -72,16 +72,16 @@ public class DoubleIDRepositoryTests {
} }
@Test @Test
public void shouldSaveDocument(){ public void shouldSaveDocument() {
//given // given
Double documentId = RandomUtils.nextDouble(); Double documentId = RandomUtils.nextDouble();
DoubleIDEntity sampleEntity = new DoubleIDEntity(); DoubleIDEntity sampleEntity = new DoubleIDEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
sampleEntity.setMessage("some message"); sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis()); sampleEntity.setVersion(System.currentTimeMillis());
//when // when
repository.save(sampleEntity); repository.save(sampleEntity);
//then // then
DoubleIDEntity entityFromElasticSearch = repository.findOne(documentId); DoubleIDEntity entityFromElasticSearch = repository.findOne(documentId);
assertThat(entityFromElasticSearch, is(notNullValue())); assertThat(entityFromElasticSearch, is(notNullValue()));
} }

View File

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

View File

@ -42,13 +42,13 @@ public class IntegerIDRepositoryTests {
private IntegerIDRepository repository; private IntegerIDRepository repository;
@Before @Before
public void before(){ public void before() {
repository.deleteAll(); repository.deleteAll();
} }
@Test @Test
public void shouldDoBulkIndexDocument(){ public void shouldDoBulkIndexDocument() {
//given // given
Integer documentId1 = RandomUtils.nextInt(); Integer documentId1 = RandomUtils.nextInt();
IntegerIDEntity sampleEntity1 = new IntegerIDEntity(); IntegerIDEntity sampleEntity1 = new IntegerIDEntity();
sampleEntity1.setId(documentId1); sampleEntity1.setId(documentId1);
@ -61,9 +61,9 @@ public class IntegerIDRepositoryTests {
sampleEntity2.setMessage("some message"); sampleEntity2.setMessage("some message");
sampleEntity2.setVersion(System.currentTimeMillis()); sampleEntity2.setVersion(System.currentTimeMillis());
//when // when
repository.save(Arrays.asList(sampleEntity1, sampleEntity2)); repository.save(Arrays.asList(sampleEntity1, sampleEntity2));
//then // then
IntegerIDEntity entity1FromElasticSearch = repository.findOne(documentId1); IntegerIDEntity entity1FromElasticSearch = repository.findOne(documentId1);
assertThat(entity1FromElasticSearch, is(notNullValue())); assertThat(entity1FromElasticSearch, is(notNullValue()));
@ -72,16 +72,16 @@ public class IntegerIDRepositoryTests {
} }
@Test @Test
public void shouldSaveDocument(){ public void shouldSaveDocument() {
//given // given
Integer documentId = RandomUtils.nextInt(); Integer documentId = RandomUtils.nextInt();
IntegerIDEntity sampleEntity = new IntegerIDEntity(); IntegerIDEntity sampleEntity = new IntegerIDEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
sampleEntity.setMessage("some message"); sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis()); sampleEntity.setVersion(System.currentTimeMillis());
//when // when
repository.save(sampleEntity); repository.save(sampleEntity);
//then // then
IntegerIDEntity entityFromElasticSearch = repository.findOne(documentId); IntegerIDEntity entityFromElasticSearch = repository.findOne(documentId);
assertThat(entityFromElasticSearch, is(notNullValue())); assertThat(entityFromElasticSearch, is(notNullValue()));
} }

View File

@ -15,7 +15,6 @@
*/ */
package org.springframework.data.elasticsearch.repository.support; package org.springframework.data.elasticsearch.repository.support;
import org.junit.Before; import org.junit.Before;
import org.junit.Ignore; import org.junit.Ignore;
import org.junit.Test; import org.junit.Test;
@ -52,15 +51,14 @@ public class SimpleElasticsearchRepositoryTests {
@Resource @Resource
private SampleElasticsearchRepository repository; private SampleElasticsearchRepository repository;
@Before @Before
public void before(){ public void before() {
repository.deleteAll(); repository.deleteAll();
} }
@Test @Test
public void shouldDoBulkIndexDocument(){ public void shouldDoBulkIndexDocument() {
//given // given
String documentId1 = randomNumeric(5); String documentId1 = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId1); sampleEntity1.setId(documentId1);
@ -73,9 +71,9 @@ public class SimpleElasticsearchRepositoryTests {
sampleEntity2.setMessage("some message"); sampleEntity2.setMessage("some message");
sampleEntity2.setVersion(System.currentTimeMillis()); sampleEntity2.setVersion(System.currentTimeMillis());
//when // when
repository.save(Arrays.asList(sampleEntity1, sampleEntity2)); repository.save(Arrays.asList(sampleEntity1, sampleEntity2));
//then // then
SampleEntity entity1FromElasticSearch = repository.findOne(documentId1); SampleEntity entity1FromElasticSearch = repository.findOne(documentId1);
assertThat(entity1FromElasticSearch, is(notNullValue())); assertThat(entity1FromElasticSearch, is(notNullValue()));
@ -84,78 +82,78 @@ public class SimpleElasticsearchRepositoryTests {
} }
@Test @Test
public void shouldSaveDocument(){ public void shouldSaveDocument() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
sampleEntity.setMessage("some message"); sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis()); sampleEntity.setVersion(System.currentTimeMillis());
//when // when
repository.save(sampleEntity); repository.save(sampleEntity);
//then // then
SampleEntity entityFromElasticSearch = repository.findOne(documentId); SampleEntity entityFromElasticSearch = repository.findOne(documentId);
assertThat(entityFromElasticSearch, is(notNullValue())); assertThat(entityFromElasticSearch, is(notNullValue()));
} }
@Test @Test
public void shouldFindDocumentById(){ public void shouldFindDocumentById() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
sampleEntity.setMessage("some message"); sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis()); sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity); repository.save(sampleEntity);
//when // when
SampleEntity entityFromElasticSearch = repository.findOne(documentId); SampleEntity entityFromElasticSearch = repository.findOne(documentId);
//then // then
assertThat(entityFromElasticSearch, is(notNullValue())); assertThat(entityFromElasticSearch, is(notNullValue()));
assertThat(sampleEntity, is((equalTo(sampleEntity)))); assertThat(sampleEntity, is((equalTo(sampleEntity))));
} }
@Test @Test
public void shouldReturnCountOfDocuments(){ public void shouldReturnCountOfDocuments() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
sampleEntity.setMessage("some message"); sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis()); sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity); repository.save(sampleEntity);
//when // when
Long count = repository.count(); Long count = repository.count();
//then // then
assertThat(count, is(greaterThanOrEqualTo(1L))); assertThat(count, is(greaterThanOrEqualTo(1L)));
} }
@Test @Test
public void shouldFindAllDocuments(){ public void shouldFindAllDocuments() {
//when // when
Iterable<SampleEntity> results = repository.findAll(); Iterable<SampleEntity> results = repository.findAll();
//then // then
assertThat(results, is(notNullValue())); assertThat(results, is(notNullValue()));
} }
@Test @Test
public void shouldDeleteDocument(){ public void shouldDeleteDocument() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
sampleEntity.setMessage("some message"); sampleEntity.setMessage("some message");
sampleEntity.setVersion(System.currentTimeMillis()); sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity); repository.save(sampleEntity);
//when // when
repository.delete(documentId); repository.delete(documentId);
//then // then
SampleEntity entityFromElasticSearch = repository.findOne(documentId); SampleEntity entityFromElasticSearch = repository.findOne(documentId);
assertThat(entityFromElasticSearch, is(nullValue())); assertThat(entityFromElasticSearch, is(nullValue()));
} }
@Test @Test
public void shouldSearchDocumentsGivenSearchQuery(){ public void shouldSearchDocumentsGivenSearchQuery() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -163,37 +161,35 @@ public class SimpleElasticsearchRepositoryTests {
sampleEntity.setVersion(System.currentTimeMillis()); sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity); repository.save(sampleEntity);
SearchQuery query = new NativeSearchQueryBuilder() SearchQuery query = new NativeSearchQueryBuilder().withQuery(termQuery("message", "test")).build();
.withQuery(termQuery("message", "test")) // when
.build();
//when
Page<SampleEntity> page = repository.search(query); Page<SampleEntity> page = repository.search(query);
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getNumberOfElements(), is(greaterThanOrEqualTo(1))); assertThat(page.getNumberOfElements(), is(greaterThanOrEqualTo(1)));
} }
@Test @Test
public void shouldSearchDocumentsGivenElasticsearchQuery(){ public void shouldSearchDocumentsGivenElasticsearchQuery() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
sampleEntity.setMessage("hello world."); sampleEntity.setMessage("hello world.");
sampleEntity.setVersion(System.currentTimeMillis()); sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity); repository.save(sampleEntity);
//when // when
Page<SampleEntity> page = repository.search(termQuery("message", "world"), new PageRequest(0,50)); Page<SampleEntity> page = repository.search(termQuery("message", "world"), new PageRequest(0, 50));
//then // then
assertThat(page, is(notNullValue())); assertThat(page, is(notNullValue()));
assertThat(page.getNumberOfElements(), is(greaterThanOrEqualTo(1))); assertThat(page.getNumberOfElements(), is(greaterThanOrEqualTo(1)));
} }
@Test @Test
@Ignore @Ignore
public void shouldFindAllByIdQuery(){ public void shouldFindAllByIdQuery() {
//todo : find solution for findAll(Iterable<Ids> ids) // todo : find solution for findAll(Iterable<Ids> ids)
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -208,16 +204,16 @@ public class SimpleElasticsearchRepositoryTests {
sampleEntity2.setVersion(System.currentTimeMillis()); sampleEntity2.setVersion(System.currentTimeMillis());
repository.save(sampleEntity2); repository.save(sampleEntity2);
//when // when
Iterable<SampleEntity> sampleEntities=repository.findAll(Arrays.asList(documentId,documentId2)); Iterable<SampleEntity> sampleEntities = repository.findAll(Arrays.asList(documentId, documentId2));
//then // then
assertNotNull("sample entities cant be null..", sampleEntities); assertNotNull("sample entities cant be null..", sampleEntities);
} }
@Test @Test
public void shouldSaveIterableEntities(){ public void shouldSaveIterableEntities() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId); sampleEntity1.setId(documentId);
@ -230,17 +226,17 @@ public class SimpleElasticsearchRepositoryTests {
sampleEntity2.setMessage("hello world."); sampleEntity2.setMessage("hello world.");
sampleEntity2.setVersion(System.currentTimeMillis()); sampleEntity2.setVersion(System.currentTimeMillis());
Iterable<SampleEntity> sampleEntities = Arrays.asList(sampleEntity1,sampleEntity2); Iterable<SampleEntity> sampleEntities = Arrays.asList(sampleEntity1, sampleEntity2);
//when // when
repository.save(sampleEntities); repository.save(sampleEntities);
//then // then
Page<SampleEntity> entities = repository.search(fieldQuery("id", documentId), new PageRequest(0, 50)); Page<SampleEntity> entities = repository.search(fieldQuery("id", documentId), new PageRequest(0, 50));
assertNotNull(entities); assertNotNull(entities);
} }
@Test @Test
public void shouldReturnTrueGivenDocumentWithIdExists(){ public void shouldReturnTrueGivenDocumentWithIdExists() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -248,65 +244,59 @@ public class SimpleElasticsearchRepositoryTests {
sampleEntity.setVersion(System.currentTimeMillis()); sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity); repository.save(sampleEntity);
//when // when
boolean exist = repository.exists(documentId); boolean exist = repository.exists(documentId);
//then // then
assertEquals(exist, true); assertEquals(exist, true);
} }
@Test @Test
public void shouldReturnResultsForGivenSearchQuery(){ public void shouldReturnResultsForGivenSearchQuery() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
sampleEntity.setMessage("hello world."); sampleEntity.setMessage("hello world.");
sampleEntity.setVersion(System.currentTimeMillis()); sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity); repository.save(sampleEntity);
//when // when
SearchQuery searchQuery = new NativeSearchQueryBuilder() SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fieldQuery("id", documentId)).build();
.withQuery(fieldQuery("id",documentId)) Page<SampleEntity> sampleEntities = repository.search(searchQuery);
.build(); // then
Page<SampleEntity> sampleEntities= repository.search(searchQuery);
//then
assertThat(sampleEntities.getTotalElements(), equalTo(1L)); assertThat(sampleEntities.getTotalElements(), equalTo(1L));
} }
@Test @Test
public void shouldDeleteAll(){ public void shouldDeleteAll() {
//when // when
repository.deleteAll(); repository.deleteAll();
//then // then
SearchQuery searchQuery = new NativeSearchQueryBuilder() SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(matchAllQuery()).build();
.withQuery(matchAllQuery()) Page<SampleEntity> sampleEntities = repository.search(searchQuery);
.build();
Page<SampleEntity> sampleEntities= repository.search(searchQuery);
assertThat(sampleEntities.getTotalElements(), equalTo(0L)); assertThat(sampleEntities.getTotalElements(), equalTo(0L));
} }
@Test @Test
public void shouldDeleteEntity(){ public void shouldDeleteEntity() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
sampleEntity.setMessage("hello world."); sampleEntity.setMessage("hello world.");
sampleEntity.setVersion(System.currentTimeMillis()); sampleEntity.setVersion(System.currentTimeMillis());
repository.save(sampleEntity); repository.save(sampleEntity);
//when // when
repository.delete(sampleEntity); repository.delete(sampleEntity);
//then // then
SearchQuery searchQuery = new NativeSearchQueryBuilder() SearchQuery searchQuery = new NativeSearchQueryBuilder().withQuery(fieldQuery("id", documentId)).build();
.withQuery(fieldQuery("id", documentId)) Page<SampleEntity> sampleEntities = repository.search(searchQuery);
.build(); assertThat(sampleEntities.getTotalElements(), equalTo(0L));
Page<SampleEntity> sampleEntities= repository.search(searchQuery);
assertThat(sampleEntities.getTotalElements(),equalTo(0L));
} }
@Test @Test
public void shouldReturnIterableEntities(){ public void shouldReturnIterableEntities() {
//given // given
String documentId1 = randomNumeric(5); String documentId1 = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId1); sampleEntity1.setId(documentId1);
@ -321,15 +311,15 @@ public class SimpleElasticsearchRepositoryTests {
sampleEntity2.setVersion(System.currentTimeMillis()); sampleEntity2.setVersion(System.currentTimeMillis());
repository.save(sampleEntity2); repository.save(sampleEntity2);
//when // when
Iterable<SampleEntity> sampleEntities = repository.search(fieldQuery("id",documentId1)); Iterable<SampleEntity> sampleEntities = repository.search(fieldQuery("id", documentId1));
//then // then
assertNotNull("sample entities cant be null..", sampleEntities); assertNotNull("sample entities cant be null..", sampleEntities);
} }
@Test @Test
public void shouldDeleteIterableEntities(){ public void shouldDeleteIterableEntities() {
//given // given
String documentId1 = randomNumeric(5); String documentId1 = randomNumeric(5);
SampleEntity sampleEntity1 = new SampleEntity(); SampleEntity sampleEntity1 = new SampleEntity();
sampleEntity1.setId(documentId1); sampleEntity1.setId(documentId1);
@ -343,33 +333,33 @@ public class SimpleElasticsearchRepositoryTests {
sampleEntity2.setVersion(System.currentTimeMillis()); sampleEntity2.setVersion(System.currentTimeMillis());
repository.save(sampleEntity2); repository.save(sampleEntity2);
Iterable<SampleEntity> sampleEntities = Arrays.asList(sampleEntity2,sampleEntity2); Iterable<SampleEntity> sampleEntities = Arrays.asList(sampleEntity2, sampleEntity2);
//when // when
repository.delete(sampleEntities); repository.delete(sampleEntities);
//then // then
assertThat(repository.findOne(documentId1),is(nullValue())); assertThat(repository.findOne(documentId1), is(nullValue()));
assertThat(repository.findOne(documentId2),is(nullValue())); assertThat(repository.findOne(documentId2), is(nullValue()));
} }
@Test @Test
public void shouldIndexEntity(){ public void shouldIndexEntity() {
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
sampleEntity.setVersion(System.currentTimeMillis()); sampleEntity.setVersion(System.currentTimeMillis());
sampleEntity.setMessage("some message"); sampleEntity.setMessage("some message");
//when // when
repository.index(sampleEntity); repository.index(sampleEntity);
//then // then
Page<SampleEntity> entities = repository.search(fieldQuery("id", documentId), new PageRequest(0,50)); Page<SampleEntity> entities = repository.search(fieldQuery("id", documentId), new PageRequest(0, 50));
assertThat(entities.getTotalElements(),equalTo(1L)); assertThat(entities.getTotalElements(), equalTo(1L));
} }
@Test @Test
public void shouldSortByGivenField(){ public void shouldSortByGivenField() {
//todo // todo
//given // given
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);
@ -381,40 +371,36 @@ public class SimpleElasticsearchRepositoryTests {
sampleEntity2.setId(documentId2); sampleEntity2.setId(documentId2);
sampleEntity2.setMessage("hello"); sampleEntity2.setMessage("hello");
repository.save(sampleEntity2); repository.save(sampleEntity2);
//when // when
Iterable<SampleEntity> sampleEntities=repository.findAll(new Sort(new Sort.Order(Sort.Direction.ASC,"message"))); Iterable<SampleEntity> sampleEntities = repository.findAll(new Sort(new Sort.Order(Sort.Direction.ASC, "message")));
//then // then
assertThat(sampleEntities,is(notNullValue())); assertThat(sampleEntities, is(notNullValue()));
} }
@Test @Test
public void shouldReturnSimilarEntities(){ public void shouldReturnSimilarEntities() {
//given // given
String sampleMessage = "So we build a web site or an application and want to add search to it, " + 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," + + "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 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 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."; + "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); List<SampleEntity> sampleEntities = createSampleEntitiesWithMessage(sampleMessage, 30);
repository.save(sampleEntities); repository.save(sampleEntities);
//when // when
SearchQuery searchQuery = new NativeSearchQueryBuilder() SearchQuery searchQuery = new NativeSearchQueryBuilder().withPageable(new PageRequest(0, 5)).withFields("message")
.withPageable(new PageRequest(0, 5))
.withFields("message")
.build(); .build();
Page<SampleEntity> results = repository.searchSimilar(sampleEntities.get(0), searchQuery); Page<SampleEntity> results = repository.searchSimilar(sampleEntities.get(0), searchQuery);
//then // then
assertThat(results.getTotalElements(), is(greaterThanOrEqualTo(1L))); assertThat(results.getTotalElements(), is(greaterThanOrEqualTo(1L)));
} }
private static List<SampleEntity> createSampleEntitiesWithMessage(String message, int numberOfEntities){ private static List<SampleEntity> createSampleEntitiesWithMessage(String message, int numberOfEntities) {
List<SampleEntity> sampleEntities = new ArrayList<SampleEntity>(); List<SampleEntity> sampleEntities = new ArrayList<SampleEntity>();
for(int i = 0; i < numberOfEntities; i++){ for (int i = 0; i < numberOfEntities; i++) {
String documentId = randomNumeric(5); String documentId = randomNumeric(5);
SampleEntity sampleEntity = new SampleEntity(); SampleEntity sampleEntity = new SampleEntity();
sampleEntity.setId(documentId); sampleEntity.setId(documentId);

View File

@ -7,12 +7,14 @@
<import resource="infrastructure.xml" /> <import resource="infrastructure.xml" />
<bean name="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate"> <bean name="elasticsearchTemplate"
<constructor-arg name="client" ref="client"/> class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="client" />
</bean> </bean>
<elasticsearch:repositories base-package="org.springframework.data.elasticsearch.repositories" /> <elasticsearch:repositories
base-package="org.springframework.data.elasticsearch.repositories" />
</beans> </beans>

View File

@ -7,8 +7,9 @@
<import resource="infrastructure.xml" /> <import resource="infrastructure.xml" />
<bean name="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate"> <bean name="elasticsearchTemplate"
<constructor-arg name="client" ref="client"/> class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="client" />
</bean> </bean>
</beans> </beans>

View File

@ -5,6 +5,7 @@
xsi:schemaLocation="http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch.xsd 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"> 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> </beans>

View File

@ -5,15 +5,18 @@
xsi:schemaLocation="http://www.springframework.org/schema/data/elasticsearch http://www.springframework.org/schema/data/elasticsearch/spring-elasticsearch-1.0.xsd 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.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" />
<bean name="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate"> <bean name="elasticsearchTemplate"
<constructor-arg name="client" ref="client"/> class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="client" />
</bean> </bean>
<elasticsearch:transport-client id="transportClient" /> <elasticsearch:transport-client id="transportClient" />
<elasticsearch:repositories base-package="org.springframework.data.elasticsearch.repositories"/> <elasticsearch:repositories
base-package="org.springframework.data.elasticsearch.repositories" />
</beans> </beans>

View File

@ -7,10 +7,11 @@
<import resource="infrastructure.xml" /> <import resource="infrastructure.xml" />
<bean name="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate"> <bean name="elasticsearchTemplate"
<constructor-arg name="client" ref="client"/> class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="client" />
</bean> </bean>
<elasticsearch:repositories base-package="org.springframework.data.elasticsearch"/> <elasticsearch:repositories base-package="org.springframework.data.elasticsearch" />
</beans> </beans>

View File

@ -7,10 +7,11 @@
<import resource="infrastructure.xml" /> <import resource="infrastructure.xml" />
<bean name="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate"> <bean name="elasticsearchTemplate"
<constructor-arg name="client" ref="client"/> class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="client" />
</bean> </bean>
<elasticsearch:repositories base-package="org.springframework.data.elasticsearch"/> <elasticsearch:repositories base-package="org.springframework.data.elasticsearch" />
</beans> </beans>

View File

@ -7,12 +7,14 @@
<import resource="infrastructure.xml" /> <import resource="infrastructure.xml" />
<bean name="elasticsearchTemplate" class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate"> <bean name="elasticsearchTemplate"
<constructor-arg name="client" ref="client"/> class="org.springframework.data.elasticsearch.core.ElasticsearchTemplate">
<constructor-arg name="client" ref="client" />
</bean> </bean>
<elasticsearch:repositories base-package="org.springframework.data.elasticsearch.repositories"/> <elasticsearch:repositories
base-package="org.springframework.data.elasticsearch.repositories" />
</beans> </beans>