### CompletionSuggester Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/suggesters.md An example demonstrating how to create and configure a CompletionSuggester. ```APIDOC **Example:** ```javascript const suggestion = esb.completionSuggester('my-completion', 'name') .text('ela') .size(10) .skipDuplicates(true); ``` ``` -------------------------------- ### Install Dependencies Source: https://github.com/sudo-suhas/elastic-builder/blob/master/CONTRIBUTING.md Install project dependencies using npm after cloning the repository. ```bash npm install ``` -------------------------------- ### Full Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md An example demonstrating the usage of terms and average aggregations within a request body. ```APIDOC ## Full Example ```javascript const esb = require('elastic-builder'); const requestBody = esb.requestBodySearch() .size(0) .agg( esb.termsAggregation('colors', 'color') .agg( esb.avgAggregation('avg_price', 'price') ) .agg( esb.termsAggregation('brands_by_color', 'brand') ) ); requestBody.toJSON(); // { // "size": 0, // "aggs": { // "colors": { // "terms": { "field": "color" }, // "aggs": { // "avg_price": { "avg": { "field": "price" } }, // "brands_by_color": { "terms": { "field": "brand" } } // } // } // } // } ``` ``` -------------------------------- ### Full Suggester Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/suggesters.md A comprehensive example showcasing the integration of term, phrase, and completion suggesters within a single search request. It includes advanced configurations like string distance, analyzers, confidence levels, max errors, and direct generators. The output is then logged to the console. ```javascript const esb = require('elastic-builder'); const request = esb.requestBodySearch() .query(esb.matchQuery('message', 'try to search')) .suggestText('teh quikc browne fox') .suggest( esb.termSuggester('term-suggestions', 'message') .size(5) .stringDistance('jaro_winkler') .analyzer('standard') ) .suggest( esb.phraseSuggester('phrase-suggestions', 'message') .size(3) .confidence(0.5) .maxErrors(2) .directGenerator( esb.directGenerator('message') .stringDistance('jaro_winkler') .maxEdits(2) ) ) .suggest( esb.completionSuggester('autocomplete', 'name') .size(10) .skipDuplicates(true) ); console.log(JSON.stringify(request.toJSON(), null, 2)); ``` -------------------------------- ### PhraseSuggester Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/suggesters.md An example demonstrating how to create and configure a PhraseSuggester. ```APIDOC ### Request Example ```javascript const suggestion = esb.phraseSuggester('my-phrase-suggestion', 'message') .text('quick browne fox') .size(5) .confidence(0.5) .maxErrors(2); ``` ``` -------------------------------- ### TermSuggester Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/suggesters.md Example of configuring a TermSuggester with various options like size, sort order, and string distance. ```javascript const suggestion = esb.termSuggester('my-suggestion', 'message', 'teh quick') .size(10) .sort('frequency') .stringDistance('jaro_winkler'); ``` -------------------------------- ### Example: GeoPoint from String Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Demonstrates creating a GeoPoint and setting its value using a string. ```javascript esb.geoPoint().string('40.7128,-74.0060') ``` -------------------------------- ### PhraseSuggester Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/suggesters.md An example demonstrating how to create and configure a PhraseSuggester with specific text, size, confidence, and max errors. ```javascript const suggestion = esb.phraseSuggester('my-phrase-suggestion', 'message') .text('quick browne fox') .size(5) .confidence(0.5) .maxErrors(2); ``` -------------------------------- ### Install elastic-builder Source: https://github.com/sudo-suhas/elastic-builder/blob/master/README.md Install the elastic-builder package using npm. This is the initial step to integrate the library into your Node.js project. ```bash npm install elastic-builder --save ``` -------------------------------- ### SimpleQueryStringQuery Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/queries.md Example of using SimpleQueryStringQuery to search for terms across specified fields. ```javascript esb.simpleQueryStringQuery('elasticsearch python') .fields(['title', 'body']) ``` -------------------------------- ### from() Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/request-body-search.md Sets the offset for pagination, determining which search hit to start from. Defaults to 0. ```APIDOC ## from(from: number) ### Description Sets the offset for pagination (which hit to start from). ### Method `from` ### Parameters #### Path Parameters - **from** (number) - Required - Number of hits to skip. Defaults to 0. ### Request Example ```javascript const reqBody = esb.requestBodySearch() .query(esb.matchAllQuery()) .from(20) .size(10); ``` ### Returns RequestBodySearch (for method chaining) ``` -------------------------------- ### Using REPL for Query Building Source: https://github.com/sudo-suhas/elastic-builder/blob/master/README.md Shows how to start the node REPL for elastic-builder and use the `esb.prettyPrint` function to format and display a constructed query. ```bash # Start the repl node ./node_modules/elastic-builder/repl.js # The builder is available in the context variable esb elastic-builder > esb.prettyPrint( ... esb.requestBodySearch() ... .query(esb.matchQuery('message', 'this is a test')) ... ); ``` ```json { "query": { "match": { "message": "this is a test" } } } ``` -------------------------------- ### Example Usage of DirectGenerator Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/suggesters.md Demonstrates how to instantiate and configure a DirectGenerator with specific parameters like field, size, string distance, and maximum edits. ```javascript const generator = esb.directGenerator('message') .size(5) .stringDistance('jaro_winkler') .maxEdits(2); ``` -------------------------------- ### Import and Use Elastic-Builder Source: https://github.com/sudo-suhas/elastic-builder/blob/master/docs/intro.md Demonstrates two ways to import and use the elastic-builder library: using the `new` keyword for class instances or using helper methods for a more concise syntax. The example shows building a simple match query. ```javascript const esb = require('elastic-builder'); // the builder // Use `new` keyword for constructor instances of class const requestBody = new esb.RequestBodySearch() .query(new esb.MatchQuery('message', 'this is a test')); // Or use helper methods which construct the object without need for the `new` keyword const requestBody = esb.requestBodySearch() .query(esb.matchQuery('message', 'this is a test')); // Build the request body requestBody.toJSON() ``` -------------------------------- ### Example Usage Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/score-functions-and-recipes.md Demonstrates how to create and use a FieldValueFactorFunction within a Function Score Query. ```APIDOC ```javascript // Boost by popularity, with logarithmic scaling const scoreFunc = esb.fieldValueFactorFunction('popularity') .factor(1.2) .modifier('log1p') .missing(1); const query = esb.functionScoreQuery() .query(esb.matchQuery('title', 'elasticsearch')) .function(scoreFunc); ``` ``` -------------------------------- ### PercolateQuery Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/queries.md Implement PercolateQuery to match documents against a set of stored queries. Specify the field and document type when initializing the query. ```javascript new esb.PercolateQuery(field?: string, documentType?: string) esb.percolateQuery(field?: string, documentType?: string) ``` -------------------------------- ### Example: Chaining Aggregations Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Demonstrates how to chain multiple aggregations, including adding a sub-aggregation with its own nested aggregation, using the fluent API. ```javascript esb.termsAggregation('colors', 'color') .agg(esb.avgAggregation('avg_price', 'price')) ``` -------------------------------- ### QueryStringQuery Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/queries.md Example of using QueryStringQuery to search for active statuses and specific titles. ```javascript esb.queryStringQuery('status:active AND (title:elasticsearch OR title:search)') ``` -------------------------------- ### Composite Aggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Creates composite buckets from multiple sources. Use this for advanced bucketing strategies, including pagination. ```javascript new esb.CompositeAggregation(name?: string) esb.compositeAggregation(name?: string) ``` -------------------------------- ### Initialize RequestBodySearch Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/request-body-search.md Instantiate the RequestBodySearch class using require or the convenience function. This is the starting point for building search requests. ```javascript const RequestBodySearch = require('elastic-builder').RequestBodySearch; const request = new RequestBodySearch(); ``` ```javascript const esb = require('elastic-builder'); const request = esb.requestBodySearch(); ``` -------------------------------- ### Highlight with Custom Tags Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Configures highlighting with custom pre and post tags for specified fields, including options for number of fragments. ```javascript const esb = require('elastic-builder'); const highlight = esb.highlight() .preTags(['']) .postTags(['']) .field('title') .field('body', { numberOfFragments: 5 }); ``` -------------------------------- ### Example: Sort by Field with Mode Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Demonstrates how to sort by a field ('price') in ascending order and apply an 'avg' mode for multi-valued fields. ```javascript esb.sort('price', 'asc').mode('avg') ``` -------------------------------- ### ScriptScoreFunction Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/score-functions-and-recipes.md Shows how to create a ScriptScoreFunction using a script to dynamically adjust scores based on document fields like 'popularity'. ```javascript const scoreFunc = esb.scriptScoreFunction() .script( esb.script() .source("_score * doc['popularity'].value") ); const query = esb.functionScoreQuery() .query(esb.matchQuery('title', 'elasticsearch')) .function(scoreFunc); ``` -------------------------------- ### Scripted Metric Aggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Configures a scripted metric aggregation with initialization, map, combine, and reduce scripts. ```javascript const esb = require('elastic-builder'); const agg = esb.scriptedMetricAggregation('total_sales') .initScript(esb.script().source("state.transactions = []")) .mapScript(esb.script() .source("state.transactions.add(doc['sales'].value)") ) .combineScript(esb.script() .source("return state.transactions.stream().sum()") ) .reduceScript(esb.script() .source("return params._aggs.stream().sum()") ); ``` -------------------------------- ### MoreLikeThisQuery Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/queries.md Instantiate MoreLikeThisQuery to find documents similar to specified items or texts. Use methods like `likeItems`, `likeTexts`, `fields`, `minTermFreq`, `maxQueryTerms`, and `minDocFreq` to configure the search. ```javascript new esb.MoreLikeThisQuery() esb.moreLikeThisQuery() ``` -------------------------------- ### RangeAggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Groups documents into user-defined ranges. Ideal for categorizing numerical data like prices. ```javascript esb.rangeAggregation('price_ranges', 'price') .range(0, 50, 'cheap') .range(50, 200, 'moderate') .range(200, null, 'expensive') ``` -------------------------------- ### RankFeatureQuery Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/queries.md Query fields that are configured as rank features using RankFeatureQuery. Initialize with the specific field name. ```javascript new esb.RankFeatureQuery(field?: string) esb.rankFeatureQuery(field?: string) ``` -------------------------------- ### Sampler Aggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Aggregates on a sample of documents. Use this for performance optimization when dealing with very large datasets and approximate results are acceptable. ```javascript new esb.SamplerAggregation(name?: string) esb.samplerAggregation(name?: string) ``` -------------------------------- ### Example Usage of CompletionSuggester Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/suggesters.md Demonstrates how to configure and use the CompletionSuggester for autocomplete. It sets the suggester name, the field to query, the prefix text, the number of results, and enables skipping duplicates. ```javascript const suggestion = esb.completionSuggester('my-completion', 'name') .text('ela') .size(10) .skipDuplicates(true); ``` -------------------------------- ### GeoHash Grid Aggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Creates a grid from geo points using geohash. Use this for spatial analysis and mapping. ```javascript new esb.GeoHashGridAggregation(name?: string, field?: string) esb.geoHashGridAggregation(name?: string, field?: string) ``` -------------------------------- ### PrefixQuery Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/queries.md Matches documents where field values start with a specified prefix. Allows setting the field and the prefix string. ```APIDOC ## PrefixQuery Matches field values starting with a prefix. ### Constructor ```javascript new esb.PrefixQuery(field?: string, prefix?: string) esb.prefixQuery(field?: string, prefix?: string) ``` ### Methods - `field(field)` - Set field - `prefix(prefix)` - Prefix to match ### Example ```javascript esb.prefixQuery('title', 'elastic') ``` ``` -------------------------------- ### DateHistogramAggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Groups documents into time-based buckets. Useful for time-series analysis. Specify interval like '1M' for monthly buckets. ```javascript esb.dateHistogramAggregation('sales_per_month', 'date') .fixedInterval('1M') ``` -------------------------------- ### Build Complex Aggregation Query Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Construct a search query with nested aggregations. This example demonstrates terms and average aggregations. ```javascript const esb = require('elastic-builder'); const requestBody = esb.requestBodySearch() .size(0) .agg( esb.termsAggregation('colors', 'color') .agg( esb.avgAggregation('avg_price', 'price') ) .agg( esb.termsAggregation('brands_by_color', 'brand') ) ); requestBody.toJSON(); // { // "size": 0, // "aggs": { // "colors": { // "terms": { "field": "color" }, // "aggs": { // "avg_price": { "avg": { "field": "price" } }, // "brands_by_color": { "terms": { "field": "brand" } } // } // } // } // } ``` -------------------------------- ### Filter Aggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Applies a filter and then aggregates matching documents. Use this to count documents that meet specific criteria. ```javascript esb.filterAggregation('active_products', esb.termQuery('status', 'active')) .agg(esb.termsAggregation('brands', 'brand')) ``` -------------------------------- ### GeoTile Grid Aggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Creates a grid from geo points using tile coordinates. Suitable for visualizing data on a map with tile-based precision. ```javascript new esb.GeoTileGridAggregation(name?: string, field?: string) esb.geoTileGridAggregation(name?: string, field?: string) ``` -------------------------------- ### WeightScoreFunction Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/score-functions-and-recipes.md Use WeightScoreFunction to multiply the score by a constant weight. This is useful for boosting or reducing the relevance of certain matches. ```javascript const scoreFunc = esb.weightScoreFunction(2.0); const query = esb.functionScoreQuery() .query(esb.matchQuery('title', 'important')) .function(scoreFunc); ``` -------------------------------- ### Filters Aggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Applies multiple filters to create separate buckets for each. Useful for categorizing documents based on different conditions. ```javascript esb.filtersAggregation('statuses') .filter('active', esb.termQuery('status', 'active')) .filter('inactive', esb.termQuery('status', 'inactive')) ``` -------------------------------- ### Geo Hex Grid Aggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Creates a hexagonal grid from geo points. This aggregation is useful for spatial analysis where hexagonal binning is preferred. ```javascript new esb.GeoHexGridAggregation(name?: string, field?: string) esb.geoHexGridAggregation(name?: string, field?: string) ``` -------------------------------- ### Initialize Highlight Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Instantiate the Highlight utility. Use `esb.highlight()` for a direct call. ```javascript new esb.Highlight() esb.highlight() ``` -------------------------------- ### AvgAggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Calculates the average of a numeric field. Use this aggregation to find the mean value of a specific field across documents. ```javascript esb.avgAggregation('avg_price', 'price') ``` -------------------------------- ### Type Safety with TypeScript Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/INDEX.md Provides examples of using TypeScript type annotations for builder objects to ensure type safety during development. ```typescript const request: esb.RequestBodySearch = esb.requestBodySearch(); const query: esb.MatchQuery = esb.matchQuery('field', 'value'); ``` -------------------------------- ### PhraseSuggester.text() Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/suggesters.md Sets the text for which to get phrase suggestions. This method is chainable. ```javascript text(text: string): PhraseSuggester ``` -------------------------------- ### Initialize KNN Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Demonstrates how to initialize a KNN object using either the constructor or a factory method. ```javascript new esb.KNN() esb.kNN() ``` -------------------------------- ### Global Aggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Aggregates all documents regardless of the query. This is useful for calculating metrics across the entire index, ignoring any filters applied by the search query. ```javascript new esb.GlobalAggregation(name?: string) esb.globalAggregation(name?: string) ``` -------------------------------- ### Constructor vs. Convenience Function Style Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/types.md Demonstrates two ways to instantiate a MatchQuery: using the class constructor or the preferred convenience function. Both are functionally equivalent. ```javascript // Constructor style const query = new esb.MatchQuery('title', 'elasticsearch'); // Convenience function style (preferred) const query = esb.matchQuery('title', 'elasticsearch'); ``` -------------------------------- ### Handle Search Results and Aggregations Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/README.md Process the response from an Elasticsearch search query. This example shows how to access individual search hits and iterate through aggregation buckets to extract relevant data. ```javascript const result = await client.search({ index: 'my-index', body: request.toJSON() }); // Access hits result.body.hits.hits.forEach(hit => { console.log(hit._source); }); // Access aggregations const buckets = result.body.aggregations.sales_over_time.buckets; buckets.forEach(bucket => { console.log(bucket.key_as_string, bucket.daily_sales.value); }); ``` -------------------------------- ### Initialize SearchTemplate Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Demonstrates how to initialize a SearchTemplate object using either the constructor or a factory method. ```javascript new esb.SearchTemplate() esb.searchTemplate() ``` -------------------------------- ### Instantiate, Configure, and Convert Query - JavaScript Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/README.md Demonstrates the builder pattern: instantiate a query, chain methods to configure it, and convert to JSON for Elasticsearch DSL. ```javascript const query = esb.matchQuery('field', 'value') .boost(2.0) .operator('and'); const dsl = query.toJSON(); ``` -------------------------------- ### Weight Score Function Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/types.md Example of using the WeightScoreFunction to multiply a score by a given weight. ```javascript esb.weightScoreFunction(weight?: number) ``` -------------------------------- ### Run Unit Tests Source: https://github.com/sudo-suhas/elastic-builder/blob/master/README.md Command to execute the project's unit tests using npm. ```bash npm test ``` -------------------------------- ### Complex Sort Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Creates a complex sort object with geo-distance, unit, and distance type. ```javascript const esb = require('elastic-builder'); const sort = esb.sort('location', 'asc') .geoDistance(esb.geoPoint().lat(40.7128).lon(-74.0060), '10km') .unit('km') .distanceType('arc'); ``` -------------------------------- ### Random Score Function Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/types.md Example of using the RandomScoreFunction to generate random scores, optionally with a seed. ```javascript esb.randomScoreFunction(seed?: number | string) ``` -------------------------------- ### Script Score Function Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/types.md Example of using the ScriptScoreFunction to compute a score based on a provided script. ```javascript esb.scriptScoreFunction(script?: Script) ``` -------------------------------- ### TermsAggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Groups documents by field value. Use this to find the most frequent values for a given field. ```javascript esb.termsAggregation('popular_colors', 'color') .size(10) .order('_count', 'desc') ``` -------------------------------- ### Highlight Constructor Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Initializes a new Highlight object or creates a highlight instance using the esb.highlight() shorthand. ```APIDOC ## Constructor Configures result highlighting. **Source:** `src/core/highlight.js` ### Constructor ```javascript new esb.Highlight() esb.highlight() ``` ``` -------------------------------- ### Runtime Field Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Defines a runtime field named 'day_of_week' with a script to extract the day of the week from a timestamp. ```javascript const esb = require('elastic-builder'); const request = esb.requestBodySearch() .query(esb.matchAllQuery()) .runtimeFields([ esb.runtimeField('day_of_week', 'keyword') .script(esb.script().source( "emit(doc['timestamp'].value.dayOfWeekEnum.getDisplayName(TextStyle.FULL, Locale.ROOT))" )) ]); ``` -------------------------------- ### Error Handling with Try-Catch Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/README.md Illustrates how to handle errors thrown immediately upon providing invalid configurations, such as incorrect enum values. ```javascript try { const query = esb.matchQuery('field', 'value') .operator('bad'); } catch (err) { console.error(err.message); // Error: The 'operator' parameter should be 'and' or 'or' } ``` -------------------------------- ### TypeScript Compile-Time Error Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/errors.md Illustrates a TypeScript compile-time error where a query type is not assignable to the expected type. ```typescript const query: MatchQuery = esb.termQuery('field', 'value'); // TypeScript error: Type 'TermQuery' not assignable to 'MatchQuery' ``` -------------------------------- ### Create a Request Body Search Query Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/INDEX.md Demonstrates using the builder pattern with method chaining to construct a search request body, including query, size, and sort parameters. ```javascript const request = esb.requestBodySearch() .query(esb.matchQuery('field', 'value')) .size(10) .sort(esb.sort('date', 'desc')); ``` -------------------------------- ### Configure Highlighting Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/configuration.md Use the `highlight` method to configure highlighting settings. Specify pre/post tags, fields to highlight, and fragment options. Multiple fields can be configured with different options. ```javascript const request = esb.requestBodySearch() .highlight( esb.highlight() .preTags(['']) .postTags(['']) .field('title') .field('body', { numberOfFragments: 5 }) ); ``` -------------------------------- ### Nested Aggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Aggregates on nested documents. Use this when you need to perform aggregations on fields within nested objects. ```javascript new esb.NestedAggregation(name?: string, path?: string) esb.nestedAggregation(name?: string, path?: string) ``` -------------------------------- ### Script Parameters Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/types.md Shows how to define scripts, including source code, language, parameters, and stored scripts. ```APIDOC ## Script Parameters Scripts can be specified as: ```javascript // As string (source code) esb.script().source("doc['field'] * 2") // With language esb.script().source("return doc['field']").lang('painless') // With parameters esb.script() .source("return doc['field'] * params.factor") .params({ factor: 2 }) // Stored script esb.script().stored('my-stored-script') ``` ``` -------------------------------- ### Basic Usage of elastic-builder Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/README.md Demonstrates how to create a basic Elasticsearch search request using elastic-builder. This includes creating a request body, adding a match query, setting the size, and converting it to JSON for use with the Elasticsearch client. ```javascript const esb = require('elastic-builder'); // Create a search request const request = esb.requestBodySearch() .query(esb.matchQuery('title', 'elasticsearch')) .size(10); // Convert to JSON for use with elasticsearch client const body = request.toJSON(); // Use with official elasticsearch client const { Client } = require('@elastic/elasticsearch'); const client = new Client({ node: 'http://localhost:9200' }); const result = await client.search({ index: 'my-index', body: body }); ``` -------------------------------- ### JavaScript Runtime Error Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/errors.md Demonstrates a JavaScript runtime error that occurs when an invalid operator is used during query execution. ```javascript const query = esb.matchQuery('field', 'value') .operator('invalid'); // Throws at this line ``` -------------------------------- ### Function vs. Class Style for Queries Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/INDEX.md Shows the recommended function style and the alternative class style for creating query objects. ```javascript // Function style (recommended) esb.matchQuery('field', 'value') ``` ```javascript // Class style new esb.MatchQuery('field', 'value') ``` -------------------------------- ### Create Query with From and Size Source: https://github.com/sudo-suhas/elastic-builder/blob/master/README.md Constructs a search query using `matchAllQuery` and specifies the `size` and `from` parameters for pagination. ```js // From / size const requestBody = esb.requestBodySearch() .query(esb.matchAllQuery()) .size(5) .from(10); requestBody.toJSON(); { "query": { "match_all": {} }, "size": 5, "from": 10 } ``` -------------------------------- ### Set Pre-Highlight Tags Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Sets the tags that will wrap highlighted terms. Defaults to ``. ```javascript esb.highlight().preTags(['', '']) ``` -------------------------------- ### Script Parameters with Elasticsearch Builder Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/types.md Shows how to define scripts, including specifying the source code, language, parameters, and using stored scripts. Use parameters to make scripts dynamic and reusable. ```javascript esb.script().source("doc['field'] * 2") ``` ```javascript esb.script().source("return doc['field']").lang('painless') ``` ```javascript esb.script() .source("return doc['field'] * params.factor") .params({ factor: 2 }) ``` ```javascript esb.script().stored('my-stored-script') ``` -------------------------------- ### Parent Aggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Aggregates parent documents. This is the counterpart to the children aggregation, allowing aggregation on parent documents from a child context. ```javascript new esb.ParentAggregation(name?: string, type?: string) esb.parentAggregation(name?: string, type?: string) ``` -------------------------------- ### Children Aggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Aggregates child documents. Use this when your data model has parent-child relationships and you want to aggregate on the child documents. ```javascript new esb.ChildrenAggregation(name?: string, type?: string) esb.childrenAggregation(name?: string, type?: string) ``` -------------------------------- ### Initialize Completion Suggester Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/suggesters.md Instantiates a new CompletionSuggester with optional name, field, and text. This suggester is ideal for implementing autocomplete features. ```javascript new esb.CompletionSuggester(name?: string, field?: string, text?: string) ``` ```javascript esb.completionSuggester(name?: string, field?: string, text?: string) ``` -------------------------------- ### Wildcard and Regex Patterns Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/types.md Explains the syntax for Wildcard and Regex patterns used in queries. ```APIDOC ## Wildcard and Regex Patterns ### Wildcard Patterns - `*` - Any characters - `?` - Single character - Prefix pattern: `user*` - Middle pattern: `use?name` ### Regex Patterns Full Java regex syntax, e.g.: - `user[0-9]+` - `test.*` - `^status.*` ``` -------------------------------- ### Create Factory Functions for Reusable Configurations Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/configuration.md Encapsulate common query patterns into factory functions to promote code reuse and consistency. ```javascript function createDateRangeFilter(field, from, to) { return esb.rangeQuery(field) .gte(from) .lte(to); } const filter = createDateRangeFilter('created_at', '2020-01-01', '2020-12-31'); ``` -------------------------------- ### RandomScoreFunction Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/score-functions-and-recipes.md Use RandomScoreFunction to generate random scores. Provide a seed for reproducible randomization, which is helpful for testing or consistent sampling. ```javascript // With seed for reproducibility const scoreFunc = esb.randomScoreFunction().seed(12345); const query = esb.functionScoreQuery() .query(esb.matchAllQuery()) .function(scoreFunc); ``` -------------------------------- ### Build Typical Request Body with elastic-builder Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/README.md Demonstrates how to programmatically construct the same Elasticsearch request body using the elastic-builder JavaScript library. ```javascript esb.requestBodySearch() .query(esb.boolQuery() .must(esb.matchQuery('title', 'elasticsearch')) .filter(esb.rangeQuery('date').gte('2020-01-01')) .should(esb.matchQuery('tags', 'tutorial')) .minimumShouldMatch(0) ) .agg(esb.termsAggregation('popular_tags', 'tags').size(10)) .sort(esb.sort('date', 'desc')) .size(20) .from(0) ``` -------------------------------- ### Validation Example: Type Error Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/README.md Shows a type error scenario where a non-numeric value is passed to the 'boost' parameter, which expects a number. ```javascript // Type error const query = esb.matchQuery('field', 'value') .boost('invalid'); // TypeError: must be number ``` -------------------------------- ### Configure Script with Parameters Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/configuration.md Pass dynamic values to scripts using the `params` object. This allows for flexible script logic. ```javascript const script = esb.script() .source("return doc['field'] * params.multiplier + params.offset") .params({ multiplier: 2, offset: 10 }); ``` -------------------------------- ### Rescore Constructor Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Instantiate a Rescore object to configure query rescoring for relevance tuning. Use either the `new` keyword or the factory method. ```javascript new esb.Rescore() ``` ```javascript esb.rescore() ``` -------------------------------- ### Type Validation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/INDEX.md Demonstrates a TypeError that occurs when an incorrect type is passed to the .query() method. Ensure you pass a Query instance. ```javascript .query('invalid') // TypeError: must be Query instance ``` -------------------------------- ### Rescore.windowSize() Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Set the window size for rescoring. Returns the Rescore instance for chaining. ```javascript windowSize(size: number): Rescore ``` -------------------------------- ### Missing Aggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Groups documents with missing field values. Use this to identify and analyze documents that lack a value for a specific field. ```javascript new esb.MissingAggregation(name?: string, field?: string) esb.missingAggregation(name?: string, field?: string) ``` -------------------------------- ### Set Post-Highlight Tags Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Sets the tags that will wrap highlighted terms. Defaults to ``. ```javascript esb.highlight().postTags(['', '']) ``` -------------------------------- ### Run Linting and Tests Source: https://github.com/sudo-suhas/elastic-builder/blob/master/CONTRIBUTING.md Execute linting and testing commands to ensure code quality and functionality. This command also handles formatting. ```bash npm run check ``` -------------------------------- ### Adjacency Matrix Aggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Creates buckets for document intersections between filters. This aggregation is useful for understanding the overlap between different sets of documents. ```javascript new esb.AdjacencyMatrixAggregation(name?: string) esb.adjacencyMatrixAggregation(name?: string) ``` -------------------------------- ### Configure Query Boost and Name Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/configuration.md Use the `boost` method to adjust relevance and `name` to identify the query. The default boost factor is 1.0. ```javascript const query = esb.matchQuery('title', 'elasticsearch') .boost(2.0) .name('my_named_query'); ``` -------------------------------- ### SimpleQueryStringQuery Constructor Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/queries.md Initializes a SimpleQueryStringQuery. Uses a simplified query syntax, a subset of Lucene. ```javascript new esb.SimpleQueryStringQuery(queryString?: string) ``` ```javascript esb.simpleQueryStringQuery(queryString?: string) ``` -------------------------------- ### Validation Example: Enum Error Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/README.md Demonstrates an enum error where an invalid string value is provided for the 'operator' parameter, which only accepts 'and' or 'or'. ```javascript // Enum error const query = esb.matchQuery('field', 'value') .operator('invalid'); // Error: operator must be 'and' or 'or' ``` -------------------------------- ### Integrate with Official Elasticsearch Client Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/INDEX.md Demonstrates how to use the Elasticsearch Builder with the official '@elastic/elasticsearch' Node.js client to send search requests. ```javascript const { Client } = require('@elastic/elasticsearch'); const esb = require('elastic-builder'); const client = new Client({ node: 'http://localhost:9200' }); const request = esb.requestBodySearch() .query(esb.matchQuery('message', 'error')); const result = await client.search({ index: 'logs', body: request.toJSON() }); ``` -------------------------------- ### Value Validation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/INDEX.md Illustrates an Error that is thrown when an invalid enum value is provided to the .operator() method. Valid values are 'and' or 'or'. ```javascript .operator('invalid') // Error: operator must be 'and' or 'or' ``` -------------------------------- ### Clone the Repository Source: https://github.com/sudo-suhas/elastic-builder/blob/master/CONTRIBUTING.md Fork the elastic-builder repository and clone it to your local machine. ```bash git clone https://github.com/your-username/elastic-builder.git ``` -------------------------------- ### Configure Search Timeout Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/configuration.md Set the search timeout duration. Supports units like 's', 'ms', 'm', 'h'. Example: '30s'. ```javascript const request = esb.requestBodySearch() .timeout('30s'); ``` -------------------------------- ### Include Explain Output for InnerHits Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Determines whether to include the 'explain' output for inner hits. Set to true to get detailed explanations. ```javascript explain(enable: boolean): InnerHits ``` -------------------------------- ### DistanceFeatureQuery Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/queries.md Boost scores based on the distance to a specified origin point using DistanceFeatureQuery. Configure the field, origin, and pivot for distance calculation. ```javascript new esb.DistanceFeatureQuery(field?: string, origin?: any, pivot?: string) esb.distanceFeatureQuery(field?: string, origin?: any, pivot?: string) ``` -------------------------------- ### Configure Source Script Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/configuration.md Define a script using its source code, language, and parameters. The default language is 'painless'. ```javascript const script = esb.script() .source("doc['field'] * params.multiplier") .lang('painless') .params({ multiplier: 2 }); ``` -------------------------------- ### ScriptQuery Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/queries.md Use ScriptQuery to filter documents based on a custom script. The `script` method accepts a Script object to define the filtering logic. ```javascript new esb.ScriptQuery(script?: Script) esb.scriptQuery(script?: Script) ``` -------------------------------- ### Search with Elasticsearch Client Source: https://github.com/sudo-suhas/elastic-builder/blob/master/README.md Demonstrates how to integrate elastic-builder with the official Elasticsearch Node.js client to perform a search query. ```js 'use strict'; const elasticsearch = require('elasticsearch'); const esb = require('elastic-builder'); const client = new elasticsearch.Client({ host: 'localhost:9200', log: 'trace' }); const requestBody = esb .requestBodySearch() .query(esb.matchQuery('body', 'elasticsearch')); client .search({ index: 'twitter', type: 'tweets', body: requestBody.toJSON() }) .then(resp => { const hits = resp.hits.hits; }) .catch(err => { console.trace(err.message); }); ``` -------------------------------- ### Script Constructor Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Initializes a new Script object. It can be called with an optional type and source. ```APIDOC ## Script Constructor Initializes a new Script object. It can be called with an optional type and source. ### Signature ```javascript new esb.Script(type?: string, source?: string) esb.script(type?: string, source?: string) ``` ### Parameters #### Path Parameters - **type** (string) - Optional - Script type: 'inline', 'source', 'stored', 'id', 'file' - **source** (string) - Optional - Script source code or identifier ``` -------------------------------- ### Significant Text Aggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Finds significant text in a field. This aggregation is useful for identifying important phrases or terms within text data. ```javascript new esb.SignificantTextAggregation(name?: string, field?: string) esb.significantTextAggregation(name?: string, field?: string) ``` -------------------------------- ### CompletionSuggester Constructor Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/suggesters.md Initializes a new instance of the CompletionSuggester. You can optionally provide a name, field, and initial text. ```APIDOC ## Constructor Provides fast prefix-based suggestions for autocomplete. ```javascript new esb.CompletionSuggester(name?: string, field?: string, text?: string) esb.completionSuggester(name?: string, field?: string, text?: string) ``` ### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | name | string | No | Suggester name | | field | string | No | Completion field to suggest from | | text | string | No | Prefix to complete | ``` -------------------------------- ### Method Chaining for Boolean Query Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/README.md Illustrates building a complex boolean query using method chaining. This approach enhances code readability for intricate query structures. ```javascript const query = esb.boolQuery() .must(esb.matchQuery('status', 'published')) .must(esb.rangeQuery('date').gte('2020-01-01')) .should(esb.matchQuery('featured', true)) .filter(esb.existsQuery('author')); ``` -------------------------------- ### Package.json Files Configuration Source: https://github.com/sudo-suhas/elastic-builder/blob/master/src/README.md This snippet shows the 'files' array in package.json, which specifies which files and directories are included when the package is published. ```json // package.json snippet { // ... // Files to be picked up by npm "files": [ "browser/", "src/", "repl.js", "index.d.ts" ], // ... } ``` -------------------------------- ### Diversified Sampler Aggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Samples documents with a diversity requirement. This ensures that the sample includes a variety of values for a specified field, preventing skewed results. ```javascript new esb.DiversifiedSamplerAggregation(name?: string) esb.diversifiedSamplerAggregation(name?: string) ``` -------------------------------- ### Create Nested Aggregations Source: https://github.com/sudo-suhas/elastic-builder/blob/master/README.md Constructs a search request with nested aggregations to perform multi-level analysis. This example shows terms, average, and nested terms aggregations. ```js // Nested Aggregation const requestBody = esb.requestBodySearch() .size(0) .agg( esb.termsAggregation('colors', 'color') .agg(esb.avgAggregation('avg_price', 'price')) .agg(esb.termsAggregation('make', 'make')) ); requestBody.toJSON(); { "size": 0, "aggs": { "colors": { "terms": { "field": "color" }, "aggs": { "avg_price": { "avg": { "field": "price" } }, "make": { "terms": { "field": "make" } } } } } } ``` -------------------------------- ### Configure Suggestions Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/configuration.md Add suggesters and global suggestion text to a search request. Use `esb.termSuggester` for term-based suggestions. ```javascript const request = esb.requestBodySearch() .suggestText('elasticsearch') .suggest(esb.termSuggester('my-suggest', 'message')); ``` -------------------------------- ### MatchAllQuery Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/queries.md Matches all documents in the index. Use the constructor or the factory function. ```javascript new esb.MatchAllQuery() ``` ```javascript esb.matchAllQuery() ``` -------------------------------- ### Reverse Nested Aggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Reverses the nesting scope to the parent document. This is useful when you need to aggregate data from parent documents after operating within a nested context. ```javascript new esb.ReverseNestedAggregation(name?: string, path?: string) esb.reverseNestedAggregation(name?: string, path?: string) ``` -------------------------------- ### Significant Terms Aggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Finds statistically significant terms in a field. Use this to identify terms that are unusually common in a subset of documents compared to the overall corpus. ```javascript new esb.SignificantTermsAggregation(name?: string, field?: string) esb.significantTermsAggregation(name?: string, field?: string) ``` -------------------------------- ### Create Aggregation with New Keyword Source: https://github.com/sudo-suhas/elastic-builder/blob/master/README.md Demonstrates creating complex nested aggregations using the `new` keyword for a more object-oriented approach. Includes filter and stats aggregations. ```js // If you prefer using the `new` keyword const agg = new esb.TermsAggregation('countries', 'artist.country') .order('rock>playback_stats.avg', 'desc') .agg( new esb.FilterAggregation('rock', new esb.TermQuery('genre', 'rock')).agg( new esb.StatsAggregation('playback_stats', 'play_count') ) ); agg.toJSON(); { "countries": { "terms": { "field": "artist.country", "order": { "rock>playback_stats.avg": "desc" } }, "aggs": { "rock": { "filter": { "term": { "genre": "rock" } }, "aggs": { "playback_stats": { "stats": { "field": "play_count" } } } } } } } ``` -------------------------------- ### order() Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Determines the order in which highlighted fragments are presented. ```APIDOC ## order() Sets fragment ordering. ```javascript order(order: string): Highlight ``` ``` -------------------------------- ### Select Stored Fields with storedFields() Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/request-body-search.md Use storedFields to specify which fields to retrieve for each document. Pass an empty array to get only _id and _type, or ['_none_'] to disable field loading. ```javascript const reqBody = esb.requestBodySearch() .query(esb.matchAllQuery()) .storedFields(['user', 'post_date']); ``` -------------------------------- ### Constructing a Full Search Request Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/request-body-search.md Build a comprehensive search request including boolean queries, range filters, aggregations, pagination, sorting, and highlighting. This is useful for complex search scenarios. ```javascript const esb = require('elastic-builder'); const request = esb.requestBodySearch() .query( esb.boolQuery() .must(esb.matchQuery('title', 'elasticsearch')) .filter(esb.rangeQuery('date').gte('2020-01-01')) ) .agg(esb.termsAggregation('categories', 'category')) .size(20) .from(0) .sort(esb.sort('date', 'desc')) .highlight(esb.highlight().field('title')); const body = request.toJSON(); // body can now be passed to elasticsearch client's search method ``` -------------------------------- ### Validate User Input for Configurations Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/configuration.md Implement validation logic before building query components, especially when accepting dynamic user input, to prevent errors. ```javascript function validateSort(field, order) { if (!['asc', 'desc'].includes(order)) { throw new Error('Invalid order: ' + order); } return esb.sort(field, order); } ``` -------------------------------- ### fields() Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Configures highlighting for multiple fields at once using an object where keys are field names and values are highlight options. ```APIDOC ## fields() Configures multiple highlight fields. ```javascript fields(fields: object): Highlight ``` **Example:** ```javascript esb.highlight().fields({ 'title': {}, 'body': { numberOfFragments: 3 } }) ``` ``` -------------------------------- ### ScriptScoreQuery Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/queries.md Modify document scores using a script with ScriptScoreQuery. Configure the base query, the scoring script, and an optional minimum score threshold using `query`, `script`, and `minScore` methods. ```javascript new esb.ScriptScoreQuery(query?: Query, script?: Script) esb.scriptScoreQuery(query?: Query, script?: Script) ``` -------------------------------- ### CardinalityAggregation Example Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/aggregations.md Counts approximate distinct values (cardinality) of a field. Use this for estimating the number of unique items when exact counts are too resource-intensive. Adjust precisionThreshold for accuracy vs. memory trade-off. ```javascript esb.cardinalityAggregation('distinct_users', 'user_id') .precisionThreshold(10000) ``` -------------------------------- ### Example: FieldValueFactorFunction in Function Score Query Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/score-functions-and-recipes.md Demonstrates how to use FieldValueFactorFunction to boost search results based on a 'popularity' field with logarithmic scaling. It also shows how to integrate this into a Function Score Query. ```javascript // Boost by popularity, with logarithmic scaling const scoreFunc = esb.fieldValueFactorFunction('popularity') .factor(1.2) .modifier('log1p') .missing(1); const query = esb.functionScoreQuery() .query(esb.matchQuery('title', 'elasticsearch')) .function(scoreFunc); ``` -------------------------------- ### Method Chaining with `this` Return Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/types.md Illustrates how most builder methods return the instance, enabling method chaining for constructing complex queries. ```javascript const query = esb.termQuery('status', 'active') .boost(2.0) .name('my_named_query'); ``` -------------------------------- ### RequestBodySearch Constructor Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/request-body-search.md Initializes a new instance of RequestBodySearch. It can be instantiated directly or using a convenience function. ```APIDOC ## Constructor ```javascript const RequestBodySearch = require('elastic-builder').RequestBodySearch; const request = new RequestBodySearch(); // or using the convenience function: const esb = require('elastic-builder'); const request = esb.requestBodySearch(); ``` ``` -------------------------------- ### toJSON() Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Converts the current Highlight configuration into a JSON object representation. ```APIDOC ## toJSON() Converts to JSON. ```javascript toJSON(): object ``` ``` -------------------------------- ### Importing from 'src' Directory Source: https://github.com/sudo-suhas/elastic-builder/blob/master/docs/intro.md Shows how to import the elastic-builder library directly from the 'src' directory, which can be used in Node.js environments version 6 and above, bypassing the default transpiled version. ```javascript const esb = require('elastic-builder/src'); ``` -------------------------------- ### Configure Match Query Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/queries.md Configures a MatchQuery with specific parameters like operator, fuzziness, and cutoff frequency. Use this to fine-tune text analysis and matching behavior. ```javascript esb.matchQuery('message', 'this is a test') .operator('and') .fuzziness('AUTO') ``` -------------------------------- ### Create Match Query using Function Style - JavaScript Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/README.md Recommended function style for creating a match query. This is equivalent to the class style but results in cleaner code. ```javascript const query = esb.matchQuery('field', 'value'); ``` -------------------------------- ### Base FunctionScoreQuery Usage Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/score-functions-and-recipes.md Demonstrates the basic structure of a FunctionScoreQuery, incorporating a match query and a random score function. ```javascript const query = esb.functionScoreQuery() .query(esb.matchQuery('title', 'elasticsearch')) .function(esb.randomScoreFunction().seed(123)) .scoreMode('multiply'); ``` -------------------------------- ### DirectGenerator Constructor Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/suggesters.md Initializes a new DirectGenerator instance. Specify the field to generate suggestions from. ```javascript new esb.DirectGenerator(field?: string) esb.directGenerator(field?: string) ``` -------------------------------- ### Configure Multiple Highlight Fields Source: https://github.com/sudo-suhas/elastic-builder/blob/master/_autodocs/api-reference/core-utilities.md Configures multiple fields for highlighting using an object. Options for each field can be specified. ```javascript esb.highlight().fields({ 'title': {}, 'body': { numberOfFragments: 3 } }) ```