Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 38 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,25 +1,46 @@
## Elasticsearch in Node.js Examples
-------------------------------
# Build a Custom Search Engine with Node.js and Elasticsearch

This repo contains examples on how to use elasticsearch in Node.js to create search functionalities.
Behrooz Kamali takes an in-depth look at elasticsearch—a scalable, high-performance search engine—demonstrating how to integrate it into a Node project.

To clone this repo in your machine:
**Article url**: https://www.sitepoint.com/search-engine-node-elasticsearch

```
git clone https://github.com/behroozk/node-elasticsearch-tutorial.git
```
## Requirements

Then, to download all the requirements:
* [Node.js](http://nodejs.org/) (min version v0.11.0)
* [Java Runtime Environment](https://java.com/en/) (min version 1.8)
* [Elasticsearch](https://www.elastic.co/)

```
npm install
```
## Installation Steps

Here is a list of all the files in this repo:
1. Clone repo
2. Run `npm install`
3. Start Elasticsearch

More precise instructions can be found in the [installation section of the article](https://www.sitepoint.com/search-engine-node-elasticsearch#installingelasticsearch)

## List of files in this repo:

1. `data.json`: sample data file
1. `index.js`: script for indexing the data in elasticsearch
1. `search.js`: search functionality
1. `filter.js`: basic filter functionality
1. `aggregations.js`: demonstration of how aggregations work
1. `suggest.js`: script for generating suggestions for search terms
2. `index.js`: script for indexing the data in elasticsearch
3. `indices.js`: script to check indexing was successful
4. `search_all.js`: return all documents in one or more indices
5. `search_match.js`: match documents that contain specific values in a field
6. `search_multi_match.js`: search within multiple fields
7. `search_match_phrase.js`: match a complete phrase
8. `search_bool.js`: combining multiple queries
9. `filter.js`: basic filter functionality
10. `aggregations.js`: demonstration of how aggregations work
11. `suggest_term.js`: generate suggestions for search terms
12. `suggest_phrase.js`: generate suggestions for search phrases

## License

The MIT License (MIT)

Copyright (c) 2016 SitePoint

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
132 changes: 66 additions & 66 deletions aggregations.js
Original file line number Diff line number Diff line change
@@ -1,77 +1,77 @@
(function () {
'use strict';
'use strict';

const elasticsearch = require('elasticsearch');
const esClient = new elasticsearch.Client({
host: '127.0.0.1:9200',
log: 'error'
});
const elasticsearch = require('elasticsearch');
const esClient = new elasticsearch.Client({
host: '127.0.0.1:9200',
log: 'error'
});

const search = function search(index, body) {
return esClient.search({index: index, body: body});
};
const search = function search(index, body) {
return esClient.search({index: index, body: body});
};

// only for testing purposes
// all calls should be initiated through the module
const test = function test() {
let body = {
size: 0, // size is set to 0 here to focus on the aggregations and not the articles
from: 0,
query: {
match_all: {}
},
aggregations: {
min_year: {
min: {field: 'year'}
},
max_year: {
max: {field: 'year'}
},
year_percentile: {
percentiles: {field: 'year'}
},
year_histogram: {
histogram: {field: 'year', interval: 5}
},
keywords: {
terms: {
field: 'keywords',
size: 20
}
}
}
};
// only for testing purposes
// all calls should be initiated through the module
const test = function test() {
let body = {
size: 0, // size is set to 0 here to focus on the aggregations and not the articles
from: 0,
query: {
match_all: {}
},
aggregations: {
min_year: {
min: {field: 'year'}
},
max_year: {
max: {field: 'year'}
},
year_percentile: {
percentiles: {field: 'year'}
},
year_histogram: {
histogram: {field: 'year', interval: 5}
},
keywords: {
terms: {
field: 'keywords',
size: 20
}
}
}
};

console.log(`retrieving documents with a combined bool query and filter (displaying ${body.size} items at a time)`);
search('library', body)
.then(results => {
console.log(`calculated aggregations in ${results.took}ms`);

console.log(`\nthe oldest article is published in ${results.aggregations.min_year.value}`);

console.log(`\nthe newest article is published in ${results.aggregations.max_year.value}`);
console.log(`retrieving documents with a combined bool query and filter (displaying ${body.size} items at a time)`);
search('library', body)
.then(results => {
console.log(`calculated aggregations in ${results.took}ms`);

console.log(`\nhistogram of number of articles published in 5-year intervals`);
results.aggregations.year_histogram.buckets.forEach(bucket => console.log(`\tnumber of articles published in ${bucket.key}-${bucket.key + 4}: ${'#'.repeat(bucket.doc_count/5)} (${bucket.doc_count})`));
console.log(`\nthe oldest article is published in ${results.aggregations.min_year.value}`);

console.log(`\npercentile of articles published in different years:`);
console.log(`\t1% of articles are published on or before ${results.aggregations.year_percentile.values['1.0']}`);
console.log(`\t5% of articles are published on or before ${results.aggregations.year_percentile.values['5.0']}`);
console.log(`\t25% of articles are published on or before ${results.aggregations.year_percentile.values['25.0']}`);
console.log(`\t50% of articles are published on or before ${results.aggregations.year_percentile.values['50.0']}`);
console.log(`\t75% of articles are published on or before ${results.aggregations.year_percentile.values['75.0']}`);
console.log(`\t95% of articles are published on or before ${results.aggregations.year_percentile.values['95.0']}`);
console.log(`\t99% of articles are published on or before ${results.aggregations.year_percentile.values['99.0']}`);
console.log(`\nthe newest article is published in ${results.aggregations.max_year.value}`);

console.log(`\ntop ${results.aggregations.keywords.buckets.length} article tags:`);
results.aggregations.keywords.buckets.forEach((bucket, index) => console.log(`\t${++index} ${bucket.key}: ${bucket.doc_count}`));
})
.catch(console.error);
};
console.log(`\nhistogram of number of articles published in 5-year intervals`);
results.aggregations.year_histogram.buckets.forEach(bucket => console.log(`\tnumber of articles published in ${bucket.key}-${bucket.key + 4}: ${'#'.repeat(bucket.doc_count/5)} (${bucket.doc_count})`));

test();
console.log(`\npercentile of articles published in different years:`);
console.log(`\t1% of articles are published on or before ${results.aggregations.year_percentile.values['1.0']}`);
console.log(`\t5% of articles are published on or before ${results.aggregations.year_percentile.values['5.0']}`);
console.log(`\t25% of articles are published on or before ${results.aggregations.year_percentile.values['25.0']}`);
console.log(`\t50% of articles are published on or before ${results.aggregations.year_percentile.values['50.0']}`);
console.log(`\t75% of articles are published on or before ${results.aggregations.year_percentile.values['75.0']}`);
console.log(`\t95% of articles are published on or before ${results.aggregations.year_percentile.values['95.0']}`);
console.log(`\t99% of articles are published on or before ${results.aggregations.year_percentile.values['99.0']}`);

module.exports = {
search
};
console.log(`\ntop ${results.aggregations.keywords.buckets.length} article tags:`);
results.aggregations.keywords.buckets.forEach((bucket, index) => console.log(`\t${++index} ${bucket.key}: ${bucket.doc_count}`));
})
.catch(console.error);
};

test();

module.exports = {
search
};
} ());
140 changes: 70 additions & 70 deletions filter.js
Original file line number Diff line number Diff line change
@@ -1,78 +1,78 @@
(function () {
'use strict';
'use strict';

const elasticsearch = require('elasticsearch');
const esClient = new elasticsearch.Client({
host: '127.0.0.1:9200',
log: 'error'
});
const elasticsearch = require('elasticsearch');
const esClient = new elasticsearch.Client({
host: '127.0.0.1:9200',
log: 'error'
});

const search = function search(index, body) {
return esClient.search({index: index, body: body});
};
const search = function search(index, body) {
return esClient.search({index: index, body: body});
};

// only for testing purposes
// all calls should be initiated through the module
const test = function test() {
let body = {
size: 20,
from: 0,
query: {
bool: {
must: [
{
query_string: {
query: '(authors.firstname:D* OR authors.lastname:H*) AND (title:excepteur)'
}
}
],
should: [
{
match: {
body: {
query: 'Elit nisi fugiat dolore amet',
type: 'phrase'
}
}
}
],
must_not: [
{
range: {
year: {
lte: 2000,
gte: 1990
}
}
}
],
filter: [
{
range: {
year: {
gte: 2011,
lte: 2015
}
}
}
]
}
}
};
// only for testing purposes
// all calls should be initiated through the module
const test = function test() {
let body = {
size: 20,
from: 0,
query: {
bool: {
must: [
{
query_string: {
query: '(authors.firstname:D* OR authors.lastname:H*) AND (title:excepteur)'
}
}
],
should: [
{
match: {
body: {
query: 'Elit nisi fugiat dolore amet',
type: 'phrase'
}
}
}
],
must_not: [
{
range: {
year: {
lte: 2000,
gte: 1990
}
}
}
],
filter: [
{
range: {
year: {
gte: 2011,
lte: 2015
}
}
}
]
}
}
};

console.log(`retrieving documents with a combined bool query and filter (displaying ${body.size} items at a time)...`);
search('library', body)
.then(results => {
console.log(`found ${results.hits.total} items in ${results.took}ms`);
if (results.hits.total > 0) console.log(`returned article titles:`);
results.hits.hits.forEach((hit, index) => console.log(`\t${body.from + ++index} - ${hit._source.title} (score: ${hit._score})`));
})
.catch(console.error);
};
console.log(`retrieving documents with a combined bool query and filter (displaying ${body.size} items at a time)...`);
search('library', body)
.then(results => {
console.log(`found ${results.hits.total} items in ${results.took}ms`);
if (results.hits.total > 0) console.log(`returned article titles:`);
results.hits.hits.forEach((hit, index) => console.log(`\t${body.from + ++index} - ${hit._source.title} (score: ${hit._score})`));
})
.catch(console.error);
};

test();
test();

module.exports = {
search
};
module.exports = {
search
};
} ());
Loading