gatsby-remark-related-posts

npm version

Calculate the similarity between posts and make it available from graphql.

To calculate the similarity, this plugin using tf-idf and Cosine similarity.

Installation

npm i --save gatsby-remark-related-posts

Usage

In your gatsby-config.js:

{
  resolve: "gatsby-remark-related-posts",
  options: {
    posts_dir: `${__dirname}/posts`,
    doc_lang: "ja",
  },
},
option description
posts_dir directory that includes your markdown files.
doc_lang ISO 639-1 language code of your post. This supports en and ja currently.

This creates a new relatedFileAbsolutePaths field on each MarkdownRemark node, like this:

// query
query {
  allMarkdownRemark {
    nodes {
      fileAbsolutePath
      fields {
        relatedFileAbsolutePaths
      }
    }
  }
}
// result
{
  "data": {
    "allMarkdownRemark": {
      "nodes": [
        {
          "fileAbsolutePath": "/home/user/blog/posts/markdown1.md",
          "fields": {
            "relatedFileAbsolutePaths": [
              "/home/user/blog/posts/markdown4.md",
              "/home/user/blog/posts/markdown2.md",
              "/home/user/blog/posts/markdown3.md"
            ]
          }
        },
        ...
      ]
    }
  }
}

These paths are sorting by similarity. In this example, first “/home/user/blog/posts/markdown4.md” is the most related to “/home/user/blog/posts/markdown1.md”.

In addition, to see all the sample code for displaying related posts, please also refer to gatsby-remark-related-posts-example.

See also this blog post(Japanese) for the motivation that created this plugin and internal algorithms.

Licence

MIT